Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Difference between foreach and grep

by velusamy (Monk)
on Dec 06, 2008 at 04:09 UTC ( [id://728481]=perlquestion: print w/replies, xml ) Need Help??

velusamy has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, Can any one give clear difference between "grep" and "foreach"?

Replies are listed 'Best First'.
Re: Difference between foreach and grep
by Lawliet (Curate) on Dec 06, 2008 at 04:41 UTC

    As the previous poster already said map and grep have similarities. But map and foreach also have similarities…silly transitive property…

    A small blurb I copy/pasted from http://www.hidemail.de/blog/perl_tutor.shtml#map_grep_foreach (bolded by moi):

    Map can select elements from an array, just like grep. The following two statements are equivalent (EXPR represents a logical expression).

    @selected = grep EXPR, @input; @selected = map { if (EXPR) { $_ } } @input;

    Also, map is just a special case of a foreach statement. The statement:

    @transformed = map EXPR, @input;

    (where EXPR is some expression containing $_) is equivalent to (if @transformed is undefined or empty):

    foreach (@input) { push @transformed, EXPR; }

    In general, use grep to select elements from an array and map to transform the elements of an array. Other array processing can be done with one of the loop statements (foreach, for, while, until, do while, do until, redo). Avoid using statements in grep/map blocks that do not affect the grep/map results; moving these "side-effect" statements to a loop makes your code more readable and cohesive.

    I'm so adjective, I verb nouns!

    chomp; # nom nom nom

      The following two statements are equivalent (EXPR represents a logical expression).

      @selected = grep EXPR, @input; @selected = map { if (EXPR) { $_ } } @input;

      That's not really true. Your second one, for each element, will be either $_ (if EXPR is true) or EXPR if it's false. The usual way to make map like grep is with the ternary operator as below.

      use Data::Dumper; my @x = qw( foo bar ); print q[ map { if (0) { $_ } } @x ], "\n"; print Dumper [ map { if (0) { $_ } } @x ]; print "\n", q[ grep 0, @x ], "\n"; print Dumper [ grep 0, @x ]; print "\n", q[ map { 0 ? $_ : () } @x ], "\n"; print Dumper [ map { 0 ? $_ : () } @x ]; __END__ map { if (0) { $_ } } @x $VAR1 = [ 0, 0 ]; grep 0, @x $VAR1 = []; map { 0 ? $_ : () } @x $VAR1 = [];
      map is just a special case of a foreach statement....

      How do you figure, because they both operate on a list? Is sum a special case of a for? foldl? foldr?

      Dear Monk, I referred the link, it gives enough vision. Thanks
Re: Difference between foreach and grep
by GrandFather (Saint) on Dec 06, 2008 at 06:07 UTC

    for/foreach is more like map than grep. foreach iterates over a list setting a loop variable as an alias to each element of the list in turn and executing a block of statements. In like fashion map iterates over a list setting a the default variable ($_) as an alias to each element of the list in turn and executing a block of statements. The difference between the two is that map returns a list containing the (probably modified) list of values.

    grep iterates over a list setting a the default variable ($_) as an alias to each element of the list in turn and executing a block of statements. grep returns a list containing the (probably unmodified) list of input element values, but omitting any for which the final statement in the block is false.

    Consider:

    use strict; use warnings; my @list = 1 .. 10; for my $loopVar (@list) { print $loopVar, ' '; ++$loopVar; } print "\n@list\n\n"; print join ' ', map {$_ -= 1; $_ - 1} @list; print "\n@list\n\n"; print join ' ', grep {$_ % 2} @list; print "\n@list\n\n";

    Prints:

    1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 1 3 5 7 9 1 2 3 4 5 6 7 8 9 10

    Perl's payment curve coincides with its learning curve.
Re: Difference between foreach and grep
by planetscape (Chancellor) on Dec 06, 2008 at 06:39 UTC
Re: Difference between foreach and grep
by spmlingam (Scribe) on Dec 06, 2008 at 06:39 UTC
Re: Difference between foreach and grep
by ikegami (Patriarch) on Dec 06, 2008 at 06:56 UTC

    There are at least 6 different kinds of for/foreach, so that's a rather vague question. More efficient to do what?

Re: Difference between foreach and grep
by kyle (Abbot) on Dec 06, 2008 at 04:13 UTC

    A lot more context would be useful here. I think they don't have much in common, actually, besides that they both loop over a list. I think grep has more in common with map than foreach.

      Dear Monk, Comparing "grep" and "foreach" which one is efficient for looping?

        As said before by many others perhaps you could describe a scenario which explains what you want to achieve, with maybe a short example then it would be easier to help you ...
        A bad example: You could also ask: which is the best editor? (For what? hmm uh?)
        Posting on PerlMonks
        But it breaks down simple to this imho:
        If asking questions its best to read it again and try to imagine the point of view from a possible helper:

        Does my question contain all that is needed to answer it from the "other side"
        without knowing what i know (and maybe forgot to write down), imagine people dont know what your current problem does look like -they also dont know your level of experience- they only see what you write, which information you provide ...

        If you are unsure if your question is too detailed (which doesnt seem to be your general problem ;-) you could provide:

        Here is a short explanation: " ... " (Try to give a quick overview, for the impatient reader).After that you could go in more detailed: Here are more details regarding my problem " ... " Maybe with "Read more" tags ...

        hth MH

        Well that depends on the reason for looping. We still need more information.

        I'm so adjective, I verb nouns!

        chomp; # nom nom nom

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://728481]
Approved by Narveson
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-03-29 04:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found