Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my Perl grep return the first match?

Tags:

grep

perl

The following snippet searches for the index of the first occurrence of a value in an array. However, when the parentheses around $index are removed, it does not function correctly. What am I doing wrong?

my ($index) = grep { $array[$_] eq $search_for } 0..$#array;
like image 888
titaniumdecoy Avatar asked Aug 11 '09 19:08

titaniumdecoy


People also ask

How do I get my first grep match?

-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.


2 Answers

The parentheses change the context in which the grep is evaluated from scalar context to list context. In scalar context grep returns the number of times the expression was true. In list context it returns the elements for which the expression was true.

The following highlights the difference context makes:

my   $x   = grep {/foo/} @array;  # the number of things that match /foo/
my  ($x)  = grep {/foo/} @array;  # the first thing that matches /foo/
my  @foo  = grep {/foo/} @array;  # all the things that match /foo/
my (@foo) = grep {/foo/} @array;  # all the things that match /foo/
like image 145
Michael Carman Avatar answered Oct 25 '22 01:10

Michael Carman


The parentheses provide a list context for grep. grep will then actually return the list of elements for which the expression was true and not just the number of times the expression was true.

like image 25
innaM Avatar answered Oct 25 '22 02:10

innaM