Number of grep number matches?

If I do the following, it $c

becomes 1

where I hoped it would be 2

, as a compact way of counting a number grep

.

my %h = (
    "abc" => undef,
    "abcd" => undef,
    "abcde" => undef
);

my $c = 0;
$c++ if grep {/bcd/} keys %h;
print $c;

      

What would be the correct way to count the number of matches grep

in this case?

+3


source to share


1 answer


Just assign the counter to grep,

my $c = grep {/bcd/} keys %h;

      



From perldoc

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

+12


source







All Articles