Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BEGIN block and variable declaration

Tags:

syntax

perl

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;
like image 374
sid_com Avatar asked Aug 24 '26 09:08

sid_com


2 Answers

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.)

like image 86
cjm Avatar answered Aug 25 '26 22:08

cjm


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
like image 45
AKHolland Avatar answered Aug 25 '26 23:08

AKHolland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!