Cristoforo has asked for the wisdom of the Perl Monks concerning the following question:
The output was:use Data::Dumper; $hash = { 'user1' => { 'oldpassword' => 0, 'filesize' => '14360', 'logins' => 1 }, 'user2' => { 'oldpassword' => 0, 'filesize' => '1220', 'logins' => 15 }, 'user3' => { 'oldpassword' => 1, 'filesize' => '1780', 'logins' => 7 } }; sub KeysByLogins { my $hash = shift; map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ $hash{$_}->{logins}, $_ ] } keys %$hash; } our @keys = KeysByLogins($hash); foreach my $key (@keys) { print Data::Dumper->Dump([$hash->{$key}], [$key]) . "\n"; # number 1 #print Data::Dumper->Dump([$hash{$key}], [$key]) . "\n"; # number + 2 } print $::{hash}. ' ', $::{keys};
The line inside the sub map { [ $hash{$_}->{logins}, $_ ] } keys %$hash; isn't using the reference notation $hash->{logins} but is referring to the hash %hash, which wasn't declared. I'm guessing it springs up from the glob(?) in the symbol table (for the duration of the sub).$user1 = { 'filesize' => '14360', 'oldpassword' => 0, 'logins' => 1 }; $user3 = { 'filesize' => '1780', 'oldpassword' => 1, 'logins' => 7 }; $user2 = { 'filesize' => '1220', 'oldpassword' => 0, 'logins' => 15 }; *main::hash *main::keys
Then, later on in the print loop, the hash ref is used in line no. 1.
If this line is commented out and line 2 is uncommented, Dumper shows the hash as empty (when accessing the undeclared %hash variable).
Would that be because %hash only springs up in the scope of the subroutine, then is inaccessible outside the sub (in the print routine).
I guess I don't understand the workings of the symbol table. Thanks for any clear explanation of this code snippet.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Question about the symbol table
by Anonymous Monk on Feb 26, 2016 at 16:12 UTC | |
by Anonymous Monk on Feb 26, 2016 at 16:25 UTC | |
|
Re: Question about the symbol table
by Cristoforo (Curate) on Feb 26, 2016 at 17:54 UTC |