Curtis Poe <[EMAIL PROTECTED]> writes:
> foreach my $user (keys %users) {
> foreach my $name (keys %{ $users{$user} } ) {
> print $users{$user}{$name},"\n";
> }
> }
>
> Note how I wrap $users{$name} in %{...} to tell Perl that I am using a hash ref here.
A way to break this down:
foreach my $user (keys %users) {
my $attr_href = $users{$user};
foreach my $name (keys %{ $attr_href } ) {
my $attr = $attr_href->{$name};
print join "--" => $user, $name, $attr;
}
}
For years, I had to take these simple steps to unwrap nested
references. I had to deal with one level at a time. I know
it seemed to waste an intermediate variable, but I couldn't
take two steps at once so I spared an intermediate variable.
It was like rock climbing -- I always put a piece of
protection in when I could. That way, I wasn't working
sooooo far from the base that I was likely to fall. I was
only a few feet above the last piece of protection.
Similarly, I couldn't take the double step that Curtis
showed you as a one-liner. I had to break it down like
this. Eventually, I could eliminate the intermediate step
(e.g. $href), but only after a lot of practice.
Oh, and using less confusing names would help a lot!!!
my %users;
my $user;
Too confusing. Which is the scalar and which is the hash,
the singular or plural one? Often, choosing good variable
names makes the problem work out better because it indicates
a well thought out design. Name a hash for the values, not
the keys.
%attrs = (
'user1' => {
'Fullname1' => 'YES'
},
'user2' => {
'Fullname2' => 'NO'
},
'user3' => {
'Fullname3' => 'YES'
}
);
foreach $user_name (keys $attrs) {
# intermediate protection
my $attr_href = $attrs{$user_name};
foreach my $attr_name (keys %{$attr_href}) {
# intermediate protection
my $attr_value = $attr_href->{$attr_name}; #
print join("--" =>
$user_name,
$attr_name,
$attr_value), # simple
"\n";
# Should be the same.
print join("++" =>
$user_name,
$attr_name,
$attrs{$user_name}{$attr_name}; # difficult
),
"\n";
}
}
--
Michael R. Wolf
All mammals learn by playing!
[EMAIL PROTECTED]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]