I have the following sample code
#!/usr/bin/perl
use strict;
use warnings;
my $b = "Size: 200 GB";
if ($b =~ /Size: (\d+) GB/) {
my $match1 = $1;
print "Match1 : $match1\n";
}
my $match2;
my $c = "Size: GB";
$c =~ /Size: (\d+) GB/;
$match2 = $1;
print "Match2 : $match2\n";
If I run this code as-is, $match2 gets the value 200 because $1 is assigned 200 from the previous block. If $c = “Size: 400 GB”, then $match2 becomes 400 because $1 values gets populated from here: $c =~ /Size: (\d+) GB/;
I can solve this problem by putting an if statement like
if ($c =~ /Size: (\d+) GB/) {
$match2 = $1;
}
But is there a better way to flush $1’s value every time ?
You’ll have to use the
if()version. Since your$cregex doesn’t the match anything, there’s no capturing done, so the previous captures are left in place. This non-reset is by design, as per http://perldoc.perl.org/perlre.html#Capture-groups :