in reply to number of matches

If you are counting characters, you can use tr//. If you are matching strings, you can use s//. Both return the number of substitutions made:

$count = ($line =~ tr/X/X/); $count = ($line =~ s/(match1|match2)/$1/g);

Just make sure you reset the position with the pos function if you are using a string (vs a single character) and you want to find overlapping matches.

HTH

Replies are listed 'Best First'.
Re^2: number of matches
by Rhandom (Curate) on Sep 03, 2004 at 14:49 UTC
    Didn't benchmark - but I believe tr/X/X/ is still modifying the string on the backend (unless there is some unknown optimization).

    It is better to leave off the second X as in tr/X//. This will not attempt to modify the string and will still return the count - as in:
    perl -e '$a="aaa"; $i=$a=~tr/a//; print "($i)($a)\n";'


    my @a=qw(random brilliant braindead); print $a[rand(@a)];