in reply to Converting a HoH to an AoA

Hi madbombX,

    I still don't really understand [map]

It took me some time to really get my mind around map the first several dozen times I encountered it, myself.

One thing that finally helped me to begin to feel more comfortable with it was to realize that map is simply an "inside-out" version of foreach.

So you can switch between the following:

foreach ( LIST ) { DO_SOMETHING_WITH-$_ }

... and ...

map { DO_SOMETHING_WITH-$_ } LIST;

Maybe that will help you as much as it helped me :)


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

Replies are listed 'Best First'.
Re^2: Converting a HoH to an AoA
by wfsp (Abbot) on Jan 19, 2007 at 20:24 UTC
    "..an "inside-out" version of foreach."
    That's a handy way of looking at map.

    I'm not so sure about:

    DO_SOMETHING_WITH-$_
    In both cases you would be changing the array. Indeed it would only work with an array (see the comment below). This is clearly your intention with the map as you've used it in void context, i.e. although map returns a list you're just throwing it away.

    It may be better to say map is useful if you want to create an array based on another array. I think: "Do something with a $_, but don't change it" would be better/safer. :-)

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @array = qw{a b c}; my @new_array = map{my $letter = $_; ++$letter} @array; print "before: @array\n"; print "after: @new_array\n"; # with some extra white space # it looks even more 'inside-out' :-) my @another = map{ my_func() } @new_array; print "another: @another\n"; print "original \@array: @array\n"; sub my_func { my $letter = $_; $letter++; return $letter; } exit; # DO_SOMETHING_WITH-$_ # doesn't work on a list for (qw{a b c}){ # this line generates: # "Modification of a read-only value attempted at..." ++$_; } # so does this map {++$_} qw{a b c};
    output:
    ---------- Capture Output ---------- > "C:\Perl\bin\perl.exe" _new.pl before: a b c after: b c d another: c d e original @array: a b c > Terminated with exit code 0.
    updated: corrected my_func sub.