in reply to how to find substring using regex

Code tags are your (and our) friends.

Your problem is that you don't store the number of matches. The following code will fix your issue.

use warnings; use strict; my $cnt = 0; my $str = "hi hi harshmane hi hi"; $cnt = ($str =~ s/(harsh)/$1/g); print "'harsh' appears $cnt times.\n"; $cnt = ($str =~ s/(hi)/$1/g); print "'hi' appears $cnt times.\n"; #OUTPUT #'harsh' appears 1 times. #'hi' appears 4 times.

Replies are listed 'Best First'.
Re^2: how to find substring using regex
by johngg (Canon) on Jun 22, 2011 at 18:16 UTC

    No need for the capture and substitution by itself!

    knoppix@Microknoppix:~$ perl -E ' > $str = q{hi hi harshmane hi hi}; > $cnt = () = $str =~ m{hi}g; > say $cnt;' 4 knoppix@Microknoppix:~$

    I hope this is of interest.



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