Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Getting a result from "foreach" block

by v_melnik (Sexton)
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!

V.Melnik

Comment on Getting a result from "foreach" block
Select or Download Code
Re: Getting a result from "foreach" block
by AppleFritter (Curate) 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!

      V.Melnik

        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 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.
Re: Getting a result from "foreach" block
by toolic (Chancellor) on Jun 25, 2014 at 12:28 UTC
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, $_; }
    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
      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 ?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1091172]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2014-09-21 08:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (167 votes), past polls