Chas. Owens wrote:
On Sun, Apr 13, 2008 at 4:03 AM, <[EMAIL PROTECTED]> wrote:
my $count = () = $str =~ /a/g;
Thanks Chas. Owens,
I need some explanation on the above on how the above regex count the
number of 'a' in a string.
With my limited understanding, this is what I thought:-
$count = () ; #To me it means $count is assigned with a undefined value
which is then assigned with a value of $str
To me $str=~/a/g is a matching test, if it match it will be 1 and if
unmatched will be 0.
snip
The match operator with option g returns different things based on its context:
#!/usr/bin/perl
use strict;
use warnings;
my $scalar = "aaaba" =~ /a/g;
my @list = "aaaba" =~ /a/g;
my $list_then_scalar = () = "aaaba" =~ /a/g;
print "scalar: $scalar list: @list list then scalar: $list_then_scalar\n";
In scalar context it returns true if it matches at all and in list
context it returns a list of matches. Now, normally a list in scalar
context returns the last element of the list,
That is the comma operator that does that. There are no commas in ().
but if you evaluate the
list in list context and then in scalar context you instead get the
number of items in the list (similar to how an array acts in scalar
context).
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/