Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Differences in BEGIN an non-BEGIN block

Tags:

perl

I have a question regarding the const declaration in perl, and could not figure out the differences, please kindly point out what are the differences.

Below is the code:

BEGIN {
  *SIZE = sub() { 2 };
}  
*ITEM = sub() { 10 };

print 'size=', SIZE, "\n";
print 'item=', &ITEM, "\n";

Now is the question, Why

  print 'item=', &ITEM, "\n";

line must have a '&' in front of ITEM, But

  print 'size=', SIZE, "\n";   

line do not need to have a '&' in front of SIZE.

And I know the BEGIN block is run at compile time.

like image 225
Huang_Hai_Feng Avatar asked Feb 17 '26 01:02

Huang_Hai_Feng


1 Answers

Because the BEGIN block is run at compile time, the compiler knows about the assignment to *SIZE, while the assignment to *ITEM hasn't happened yet.

Because the compiler doesn't know about *ITEM, calls to ITEM are ambiguous, thus you must prefix it with an &. Otherwise, the compiler thinks it could be a "bare word" -- an unquoted string.

If you use strict, the compile will assume that bare words are functions.

use constant may also be a better way to declare constants, rather than doing it manually.

like image 111
Sean McMillan Avatar answered Feb 19 '26 19:02

Sean McMillan



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!