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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With