Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Getting a result from "foreach" block

by v_melnik (Scribe)
on Jun 25, 2014 at 11:42 UTC ( #1091172=perlquestion: print w/replies, xml ) Need Help??
v_melnik has asked for the wisdom of the Perl Monks concerning the following question:

Dear colleagues,

I tried to google the answer, but haven't successed, so I'll be grateful for your help.

How can I get some list of results of some "foreach" loop? Just something like that:

my @results = foreach (@data) { $_ = $_ * 13; # some command to add the element to the resulting list # kind of push(), but how to get the reference # to the resulting array? }

Right now I'm using the following construction that I don't like:

@results = eval { my @r; foreach (@data) { $_ = $_ * 13; push(@r); } return(@r); }

Of course, I'm not too happy with that. How does the best way look like?

Lots of thanks to all for hints, tips and ideas!


Replies are listed 'Best First'.
Re: Getting a result from "foreach" block
by AppleFritter (Vicar) on Jun 25, 2014 at 11:47 UTC

    May the more enlightened members of the monastery correct me if I'm wrong, but foreach is a control construct. It does not return a value; it controls the execution of your code.

    What you want is map, which takes a list, performs a operation on each element and returns the resulting list of processed elements:

    #!/usr/bin/perl use strict; my @array = (1, 2, 3, 4, 5); my @results = map { $_ * 13 } @array; # @results is (13, 26, 39, 52, 65)

      Wow, great, thank you!

      Such a shame I have never used map() before!


        You're welcome! Keep map and grep in mind, they're among the most useful functions you'll ever see for list processing.

        For more useful list-related functions, see e.g. List::Util. (In particular, this contains a reduce function that sadly does not exist as a builtin.)

Re: Getting a result from "foreach" block
by CountZero (Bishop) on Jun 25, 2014 at 14:28 UTC
    What stops you from doing the following:
    my @results; foreach (@data) { $_ = $_ * 13; push @results, $_; }
    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;


    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
      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 ?

Re: Getting a result from "foreach" block
by toolic (Bishop) on Jun 25, 2014 at 12:28 UTC
Re: Getting a result from "foreach" block
by Anonymous Monk on Jun 25, 2014 at 12:02 UTC
    Or, for more general cases, simply use foreach, and/or the each() function, to control an ordinary loop, and do whatever needs to be done within that loop. The aforementioned functions are of course very efficient and are great for avoiding the necessity of explicit loops. Feel free to do it either way as suits the occasion.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1091172]
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2018-05-21 17:21 GMT
Find Nodes?
    Voting Booth?