Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Perl Idioms Explained - @ary = $str =~ m/(stuff)/g

by bart (Canon)
on Sep 17, 2003 at 10:15 UTC ( #292089=note: print w/ replies, xml ) Need Help??

in reply to Perl Idioms Explained - @ary = $str =~ m/(stuff)/g

$num_matches_stuff = $str =~ m/(stuff)/g; @all_the_matches = $str =~ m/(stuff)/g;
In scalar context we get the count of the matches, in array context we get the matches.
No, the former just is not right. You haven't actually tried it, have you?
$str = "stuff stuff stuff"; $num_matches_stuff = $str =~ m/(stuff)/g; print $num_matches_stuff;

The /g modifier in scalar context is very special. It is intended to be used in a loop, something like this:

$str = "stuff stuff stuff"; while($str =~ m/(stuff)/g) { print "Got one!\n"; }
Got one!
Got one!
Got one!
So in scalar context, it will match at most once at a time — next time around, it'll continue where it left off last time.

Therefore, the returned valued of //g when used in scalar context is either 0, or 1.

Comment on Re: Perl Idioms Explained - @ary = $str =~ m/(stuff)/g
Select or Download Code
Replies are listed 'Best First'.
Re: Re: Perl Idioms Explained - @ary = $str =~ m/(stuff)/g
by tachyon (Chancellor) on Sep 17, 2003 at 13:15 UTC

    Hmm it is of course as you say. I must have got myself confused with the behaviour of s///.

    $data = 'stuff stuff stuff'; $num = $data =~ s/(stuff)//g; print $num, $/; __DATA__ 3

    You can force it to do as I said by cheating thusly....

    $num = () = 'stuff stuff stuff' =~ m/(stuff)/g; print $num; __DATA__ 3




Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2015-11-25 03:57 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (670 votes), past polls