http://www.perlmonks.org?node_id=1017420


in reply to Using grep in a scalar context

You say the approach you are using is "not working", leaving us to guess what data you are using and what result you expect.

My guesses are that either you want to count the number of strings in a dataset (i.e., an array) in which a pattern occurs at least once, or you want to count the total occurrences of a pattern in all strings in a dataset.

The code you posted seems to serve for the first purpose. A variation using map seems to take care of the other. (Note that the pattern occurs twice in 'zAAzAAz'.) In neither case is the original dataset changed.

>perl -wMstrict -le "my @FMat; my @dipept = qw(xAAx yAAy xyzzy zAAzAAz zzzz); ;; $FMat[0][0] = grep(/AA/, @dipept); print qq{grepped: $FMat[0][0]}; ;; $FMat[0][0] = map /AA/g, @dipept; print qq{mapped: $FMat[0][0]}; ;; print qq{@dipept}; " grepped: 3 mapped: 4 xAAx yAAy xyzzy zAAzAAz zzzz

Update: Do we need to consider the question of overlapping versus non-overlapping pattern matches? I.e., How many matches are there in 'xAAAx'?