When trying to use typeglob for aliasing purposes, I ran into a strange behavior. I wonder if someone could explain the logic behind.
The following code (trying to access the hash directly as %foo) does not work:
use strict; use warnings; my $hashref = { "key" => "value" }; local *foo = $hashref; printf("keys=%d\n", scalar(keys(%foo)));
I get both 'Variable "%foo" is not imported' (which I find weird) and 'Global symbol "%foo" requires explicit package name' (which explains the problem). So far so good.
Attempting to use "my", the code now executes (with a warning: 'Name "main::foo" used only once: possible typo') but I do not get the expected result:
use strict; use warnings; my $hashref = { "key" => "value" }; my %foo; local *foo = $hashref; printf("keys=%d\n", scalar(keys(%foo))); # prints: keys=0
Using "our" instead of "my", I do get the expected result:
use strict; use warnings; my $hashref = { "key" => "value" }; our %foo; local *foo = $hashref; printf("keys=%d\n", scalar(keys(%foo))); # prints: keys=1
Could someone please explain why the "my" version is good enough to make Perl happy while still returning an unexpected result?
In reply to typeglob & my | our by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |