Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: how to find substring using regex

by zek152 (Pilgrim)
on Jun 22, 2011 at 17:29 UTC ( [id://910946]=note: print w/replies, xml ) Need Help??


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.

    Cheers,

    JohnGG

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://910946]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2026-01-16 06:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (118 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.