At 05:08 PM 6/14/2001, you wrote:
>Try:
>$result = $string =~ /a/g;
>The value will be in $result
>
>Carl
Close. You have to force list context for the result of the pattern match
to make it work. Like this:
$result = () = $string =~ /a/g;
(Thanks to Mark-Jason Dominus)
Check out perlop for a note about why the first example won't work:
(in the section called 'Binding Operators':
<docs>
Binary ``=~'' binds a scalar expression to a pattern match.
<snip>
When used in scalar context, the return value generally indicates the
success of the operation. Behavior in list context depends on the
particular operator. See Regexp Quote-Like Operators for details.
</docs>
And, if we follow the pointer we read:
<docs>
If the /g option is not used, m// in list context returns a list consisting
of the subexpressions matched by the parentheses in the pattern, i.e., ($1,
$2, $3...). (Note that here $1 etc. are also set, and that this differs
from Perl 4's behavior.) When there are no parentheses in the pattern, the
return value is the list (1) for success. With or without parentheses, an
empty list is returned upon failure.
</docs>
So, looking back at the solution:
$result = () = $string =~ /a/g;
We're getting the result of globally matching the pattern against the
string, in list context (the () is an empty list, which we are populating
with the 1's that are returned by =~ as the matching is done) then we
evaulate that list in scalar context, which yields the number of elements
in it. The empty list there is important, otherwise the results of =~ are
evaluated in scalar context, yielding only a 1 or 0 for success or failure.
Check it out:
$string = 'aaaaa';
$result1 = () = $string =~ /a/g;
$result2 = $string =~ /a/g;
print "$result1\n$result2";
Later,
Sean.