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;
-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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With