简体   繁体   中英

BEGIN block and variable declaration

Is it valid perl to set a variable in a BEGIN block, but declare the variable outside the BEGIN block?

#!/usr/bin/env perl
use strict;
use warnings;
use 5.10.0;

my $var;

BEGIN{ $var = 10 }

say $var;

Yes, it's valid. In fact, you must do it that way, or $var would be local to the BEGIN block and not available in the rest of your program. To quote perlsub :

A my has both a compile-time and a run-time effect. At compile time, the compiler takes notice of it. ... Actual initialization is delayed until run time, though, so it gets executed at the appropriate time, such as each time through a loop, for example.

The compile-time effect is why you can access the variable in the BEGIN block. Be aware that any initialization on the my will take place after the BEGIN block is evaluated (and thus will overwrite any value the BEGIN might set.)

Yes, but you might want to be careful with this pattern, because something very similar will work differently than you might expect:

my $var = 5;
BEGIN { $var = 10 }

say $var; # 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM