"..an "inside-out" version of foreach."That's a handy way of looking at map.
I'm not so sure about:
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.DO_SOMETHING_WITH-$_
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. :-)
output:#!/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};
updated: corrected my_func sub.---------- 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.
In reply to Re^2: Converting a HoH to an AoA
by wfsp
in thread Converting a HoH to an AoA
by madbombX
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |