Re: Curious plperl behavior

Поиск
Список
Период
Сортировка
От Jeff
Тема Re: Curious plperl behavior
Дата
Msg-id F03C8D78-F4E1-47E3-92F4-89DC08B0E872@torgo.978.org
обсуждение исходный текст
Ответ на Curious plperl behavior  (Jeff <threshar@torgo.978.org>)
Ответы Re: Curious plperl behavior  (Tom Lane <tgl@sss.pgh.pa.us>)
Список pgsql-general
On Feb 24, 2010, at 8:44 AM, Jeff wrote:
>
> Notice on the second run the plan is still "beef" when it was set to
> 49abf0 (which when passed as the arg is correct)
> Any perl gurus have any further info on this?  It was a bit
> surprising to encounter this.  I'm guessing it has something to do
> with variable scope and the fact plperl funcs are just anonymous
> functions.
>
> Stuffing it in $_SHARED seems to work fine and ends up with results
> as one would expect.
>

Thanks to RhodiumToad on irc for the pointer - posting this here for
posterity.

 From perlref:

"Thus is because named subroutines are created (and
        capture any outer lexicals) only once at compile time, whereas
anony-
        mous subroutines get to capture each time you execute the
'sub' opera-
        tor. If you are accustomed to using nested subroutines in
other pro-
        gramming languages with their own private variables, you'll
have to
        work at it a bit in Perl.  The intuitive coding of this type
of thing
        incurs mysterious warnings about "will not stay shared".  For
example,
        this won't work:

            sub outer {
                my $x = $_[0] + 35;
                sub inner { return $x * 19 }   # WRONG
                return $x + inner();
            }

        A work-around is the following:

            sub outer {
                my $x = $_[0] + 35;
                local *inner = sub { return $x * 19 };



                return $x + inner();
            }

        Now inner() can only be called from within outer(), because of
the tem-
        porary assignments of the closure (anonymous subroutine).  But
when it
        does, it has normal access to the lexical variable $x from the
scope of
        outer().


--
Jeff Trout <jeff@jefftrout.com>
http://www.stuarthamm.net/
http://www.dellsmartexitin.com/




В списке pgsql-general по дате отправления:

Предыдущее
От: Richard Huxton
Дата:
Сообщение: Re: Cast char to number
Следующее
От: "Joshua D. Drake"
Дата:
Сообщение: Re: Cast char to number