in reply to Re: Getting a result from "foreach" block
in thread Getting a result from "foreach" block

What stops you ...

Nothing stops the beginner from using the first approach or from pitching headlong into the yawning chasm it opens up, for the  foreach loop is mutating the  @data "source" array. Of course, map also aliases  $_ to the items of the list over which it iterates and so presents the same pitfall, but I agree it is the idiomatic and preferable approach — but let beginners beware!

c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my @data = 1 .. 4; dd \@data; ;; my @results; foreach (@data) { $_ = $_ * 13; push @results, $_; } ;; dd \@data; dd \@results; " [1 .. 4] [13, 26, 39, 52] [13, 26, 39, 52]

Replies are listed 'Best First'.
Re^3: Getting a result from "foreach" block
by RonW (Parson) on Jun 26, 2014 at 17:18 UTC

    Then why not:

    my @results; foreach (@data) { push @results, $_ * 13; }

    To avoid the mutation of @data ?

      Better, IMHO, is  my @result = map $_ * 13, @data; as already suggested by AppleFritter and CountZero. (Better because more concise and expressive, and it just leaves  $_ the heck alone.)