Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number grep matches?

If I do the following, the $c becomes 1 where I was hoping it would be 2, as a compact way to count the number of grep matches.

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 grep matches in this case?

like image 894
Jasmine Lognnes Avatar asked Dec 12 '22 03:12

Jasmine Lognnes


1 Answers

Just assign counter to grep,

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

From perldoc

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

like image 62
mpapec Avatar answered Jan 06 '23 18:01

mpapec