BEGIN and lexical variables inside subroutines

3 views
Skip to first unread message

Benjamin Smith

unread,
May 12, 2005, 4:06:48 PM5/12/05
to perl6-l...@perl.org
sub foo { my $x; BEGIN { $x = 3 }; say $x }
foo; foo; foo;

Currently in perl5 and pugs this prints "3\n\n\n".

Should BEGIN blocks be able to modify values in lexical variables that
don't really exist yet? (People can use state after all to get a
variable which does exist early enough for them to modify.)


Is there some kind of "prototype pad" (and lexicals) available inside
the BEGIN block, rather than a full runtime pad?

--
Benjamin Smith <bsm...@vtrl.co.uk, benjami...@yahoo.co.uk>

Dave Mitchell

unread,
May 12, 2005, 6:18:10 PM5/12/05
to Benjamin Smith, perl6-l...@perl.org
On Thu, May 12, 2005 at 09:06:48PM +0100, Benjamin Smith wrote:
> sub foo { my $x; BEGIN { $x = 3 }; say $x }
> foo; foo; foo;
>
> Currently in perl5 and pugs this prints "3\n\n\n".
>
> Should BEGIN blocks be able to modify values in lexical variables that
> don't really exist yet? (People can use state after all to get a
> variable which does exist early enough for them to modify.)
>
>
> Is there some kind of "prototype pad" (and lexicals) available inside
> the BEGIN block, rather than a full runtime pad?

In perl5, the first instance of a lexical exists from the moment of
compilation through till first exit from the enclosing scope during
exection. If this wasn't the case then lots of closure-related stuff
wouldn't work, eg

{
my $count = 0;
sub inc { $count++ }
sub dec { $count-- }
}
...

--
print+qq&$}$"$/$s$,$*${d}$g$s$@$.$q$,$:$.$q$^$,$@$*$~$;$.$q$m&if+map{m,^\d{0\,},,${$::{$'}}=chr($"+=$&||1)}q&10m22,42}6:17*2~2.3@3;^2dg3q/s"&=~m*\d\*.*g

Larry Wall

unread,
May 14, 2005, 12:43:01 PM5/14/05
to perl6-l...@perl.org
On Fri, May 13, 2005 at 04:21:25PM +0200, "TSa (Thomas Sandlaß)" wrote:
: And I hope that it is not possible to accidentially
: mess up the internals of the compiler because code
: in a BEGIN hits compiler data.

Whereas I hope that it *is* possible to intentionally
mess up the internals of the compiler because code
in a BEGIN has access to compiler data.

The compiler is not immutable; it is a means to an end.
And the end I am imagining is one that I cannot imagine.

Larry

Reply all
Reply to author
Forward
0 new messages