The second print statement print '4', because you have used /g in your first statement in a scalar context, so the position of the digits to count is less than one, thus the value '4' was printed. Please, note that as long as your match didn't fail, your position changes
check this:
#!/usr/bin/perl
use strict;
use warnings;
my $a=" 456 789 123 456 789 ";
my $count;
$count=$a =~ /\d+/g;
print "$count\n"; # output '1', position changes
$count=$a =~ /\d+/g;
print "$count\n"; # output '1' position changes
$count = () = $a =~ /\d+/g;
print "$count\n"; # output '3'
my @a = $a =~ /\d+/g;
$count = @a;
print "$count\n";
if you wanted to get '5', at the second print (a) remove the /g, then the second print gives you a '5', like this:
#!/usr/bin/perl
use strict;
use warnings;
my $a=" 456 789 123 456 789 ";
my $count;
$count=$a =~ /\d+/;
print "$count\n";
$count = () = $a =~ /\d+/g;
print "$count\n";
my @a = $a =~ /\d+/g;
$count = @a;
print "$count\n";
(b) In another case, you can do this:
#!/usr/bin/perl
use strict;
use warnings;
my $a=" 456 789 123 456 789 ";
my $count;
my $b=$a;
$count=$a =~ /\d+/g;
print "$count\n";
$count = () = $b =~ /\d+/g;
print "$count\n";
my @a = $b =~ /\d+/g;
$count = @a;
print "$count\n";
Hope this helps. |