Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

To newbie me, it seems that this behavior:
my $s=',,,,'; @nCommas=($s=~/,/g); $nCommas=@nCommas; print "$nCommas\n"; # prints 4
is not consistent with this behavior:
my $s=',,,,'; $nCommas=($s=~/,/g); print "$nCommas\n"; # prints 1
Why isn't $nCommas equal to 4 in the second example? Thanks!

Replies are listed 'Best First'.
Re: context conversions: seeking enlightenment
by Anonymous Monk on Apr 18, 2002 at 19:57 UTC
    I apologize for not reading further--this seems to be due to my confusing lists and arrays. If that's not the issue, I'd appreciate any help. Otherwise sorry to waste bandwidth.

      Well, I can see two potential sources of confusion.

      First, the less likely one. Some think that parens (()) impose a list context. So you might think that $s=~/,/g is in a list context here:

      my $s=',,,,'; $nCommas=($s=~/,/g);
      but it is not. Those parens just make the grouping explicit. [Parens are often used when building lists. And using parens on the left side of an assignment does provide a list context to the right side.]

      Second, m/.../g should (usually) only be used in a scalar context as part of a loop. Each time m/.../g is used in a scalar context, only the single next match is found (see pos for some more information).

      So in the second block, Perl has only found the first comma and doesn't yet know that there are 4 commas.

      Alternatives to your first method include:

      my $s=',,,,'; print $s =~ tr/,//; my $count= ()= $s=~/,/g; print $count; print 0+( ()= $s=~/,/g );
      See also perldoc perlre and Regexp operators (in perldoc perlop).

              - tye (but my friends call me "Tye")