[San-Diego-pm] map HoAoA
Randal L. Schwartz
merlyn at stonehenge.com
Thu Oct 7 10:44:56 PDT 2010
>>>>> "Mike" == Mike McClain <mike.junk at nethere.com> writes:
Mike> First let me say that this is self assigned homework just for my
Mike> own education, I'm not in class.
Mike> Reading perldsc and perllol I thought to pull the second item from
Mike> each array of a HoAoA (hash of arrays of arrays) using a map statement
Mike> but after several days of flailing still haven't found a solution nor
Mike> do I even understand why I'm not getting what I want.
Mike> Here's a code segment, strict and warnings are turned on just not
Mike> shown.
Mike> { my %HoAoA = (
Mike> a => [ [ qw / aa1 aa2 / ], [ qw / ab1 ab2 / ] ],
Mike> b => [ [ qw / ba1 ba2 / ], [ qw / bb1 bb2 / ] ],
Mike> c => [ [ qw / ca1 ca2 / ], [ qw / cb1 cb2 / ],
Mike> [ qw / cc1 cc2 / ] ],
Mike> );
Mike> # this gets refs to all arrays
Mike> my @aRefs = map { @{ $HoAoA{$_} } [ 0..$#{ $HoAoA{$_} } ] } keys %HoAoA ;
Mike> # pull second entry from each array
Mike> for my $a ( @aRefs )
Mike> { print "$a = $$a[1]\n";
Mike> }
Mike> # This is the statement I'm having trouble with:
Mike> # If you can explain why I'm only getting the second entry from the
Mike> # last array of each hash entry then perhaps I can figure out how
Mike> # to get the second entry from all arrays
Mike> my @seconds = map { @{ $HoAoA{$_} } [ 0..$#{ $HoAoA{$_} } ]->[1] }
Mike> keys %HoAoA ;
Mike> print "\@seconds = @seconds\n";
Mike> }
Start with the values, not the keys. You don't need the keys:
my @first_level_array_refs = values %HoAoA;
Now you want all the second-level array refs, in order:
my @second_level_array_refs = map { @$_ } @first_level_array_refs;
And then you want the second element of each:
my @seconds = map { $_->[1] } @second_level_array_refs;
Putting it all together:
my @seconds = map { $_->[1] } map { @$_ } values %HoAoA;
And no, you can't shortcut that very much more than that.
--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion
More information about the San-Diego-pm
mailing list