in reply to grep surprise

RTFM?

grep

In scalar context, returns the number of times the expression was true.

and it's $i3 not i3

anyway others may profit from a working solution, just replacing grep with first

use strict; use warnings; use List::Util qw/first/; my @array=(1,2); my $i1 = first { $array[$_] == 1 } (0..$#array); my $i2 = first { $array[$_] == 2 } (0..$#array); my $i3 = first { $array[$_] == 3 } (0..$#array); print "<$i1> <$i2> <$i3>\n";
Use of uninitialized value $i3 in concatenation (.) or string at d:/tm +p/first.pl line 13. <0> <1> <>

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Replies are listed 'Best First'.
Re^2: grep surprise
by morgon (Priest) on Nov 11, 2018 at 23:52 UTC
    ikegami shows the way to do it above.

    Using List::Util::first works of course but does not add any value at all.

      > does not add any value at all.

      Not very surprising that you think that way.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        How about the value of verbosity?
        $ perl -we ' use strict; my @array=(1,2); my $matches = 0; for my $ea (1..3) { $matches = grep { printf("idx: %d, val: %d == %d? %3s, ", $_, $array[$_], $ea, ($array[$_] == $ea) ? "YES" : "NO"); $array[$_] == $ea; } (0..$#array); print "matches: $matches\n"; } ' __output__ idx: 0, val: 1 == 1? YES, idx: 1, val: 2 == 1? NO, matches: 1 idx: 0, val: 1 == 2? NO, idx: 1, val: 2 == 2? YES, matches: 1 idx: 0, val: 1 == 3? NO, idx: 1, val: 2 == 3? NO, matches: 0

        and who ever said Perl was not readable... :)

      A reply falls below the community's threshold of quality. You may see it by logging in.