in reply to Getting a result from "foreach" block

What stops you from doing the following:
my @results; foreach (@data) { $_ = $_ * 13; push @results, $_; }
or
my @results; push @results, $_*13 for @data;
You will find the "return" of the loop in @results.

The most "perlish" way of doing such a thing of course uses map (as AppleFritter already said]:

my @results = map $_*13, @data;

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

My blog: Imperial Deltronics

Replies are listed 'Best First'.
Re^2: Getting a result from "foreach" block
by AnomalousMonk (Archbishop) on Jun 25, 2014 at 18:51 UTC
    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]

      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.)