Hi,
I was tempted to post this to the "Perl News" section ... but then I figured that, although it was "news to me", it probably wasn't to many of those that peruse this forum. (Actually, I'm not even sure that this *is* "news to me" ... there's an unsettling deja-vu that has me scanning the horizon for eggs heading my way.)
The demo is:
use warnings;
use subs qw(non_commutative);
sub non_commutative {return 17}
$x = 10 * non_commutative;
$y = non_commutative * 10;
print "$x\n$y\n\n";
$x = 10 + non_commutative;
$y = non_commutative + 10;
print "$x\n$y\n";
__END__
Outputs:
170
17
27
17
and the output proves, without any shadow of a doubt, that neither multiplication nor addition are commutative.
The thing that amazes me the most is that the subs documentation says simply:
This will predeclare all the subroutine whose names are in the list, allowing you to use them without parentheses even before they're declared.But that is clearly not so - *including* the parentheses in the above script alters the output (and restores commutativity):
use warnings;
use subs qw(non_commutative);
sub non_commutative {return 17}
$x = 10 * non_commutative();
$y = non_commutative() * 10;
print "$x\n$y\n\n";
$x = 10 + non_commutative();
$y = non_commutative() + 10;
print "$x\n$y\n";
__END__
Outputs:
170
170
27
27
That's a fairly significant caveat that has been ignored in the subs documentation.
The docs do go on to say:
Unlike pragmas that affect the $^H hints variable, the "use vars" and
"use subs" declarations are not BLOCK-scoped. They are thus effective
for the entire file in which they appear. You may not rescind such
declarations with "no vars" or "no subs".
See "Pragmatic Modules" in perlmodlib and "strict subs" in strict.Is this explained in either "Pragmatic Modules" or "strict subs" ? ... I wouldn't expect so, though apathy has prevented me from actually checking.
I guess there's a good explanation documented somewhere ?
Cheers,
Rob
UPDATE: Added the ouptuts my demos were producing. Thanks
JavaFan.