Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: typeglob & my | our
by LanX (Saint) on Mar 07, 2012 at 13:26 UTC | |
|
Re: typeglob & my | our
by JavaFan (Canon) on Mar 07, 2012 at 14:35 UTC | |
by LanX (Saint) on Mar 07, 2012 at 14:40 UTC | |
by JavaFan (Canon) on Mar 07, 2012 at 16:25 UTC | |
by LanX (Saint) on Mar 07, 2012 at 16:30 UTC | |
|
Re: typeglob & my | our
by ikegami (Patriarch) on Mar 08, 2012 at 02:19 UTC |