$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;
Result: 1
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";
}
Result:
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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|