From: | Jeff <threshar(at)torgo(dot)978(dot)org> |
---|---|
To: | Jeff <threshar(at)torgo(dot)978(dot)org> |
Cc: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: Curious plperl behavior |
Date: | 2010-02-24 20:36:53 |
Message-ID: | F03C8D78-F4E1-47E3-92F4-89DC08B0E872@torgo.978.org |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | 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(at)jefftrout(dot)com>
http://www.stuarthamm.net/
http://www.dellsmartexitin.com/
From | Date | Subject | |
---|---|---|---|
Next Message | Joshua D. Drake | 2010-02-24 20:38:22 | Re: Cast char to number |
Previous Message | Richard Huxton | 2010-02-24 20:36:39 | Re: Cast char to number |