I have to admit, this one has me foxed.
Consider this code:
use version;
use Data::Dumper;
my $codeLevel = q{6.1.0.7 (build 25.3.1103030000)};
print STDERR qq{$codeLevel\n};
my $vrmf;
if($codeLevel =~ /^\s*([0-9.]*) \(build.*\)/) {
print STDERR "$1\n";
$vrmf = version->parse($1);
}
print STDERR Dumper($vrmf);
The output, as expected, is:
6.1.0.7 (build 25.3.1103030000)
6.1.0.7
$VAR1 = bless( {
'original' => '6.1.0.7',
'qv' => 1,
'version' => [
6,
1,
0,
7
]
}, 'version' );
However, remove the second print:
use version;
use Data::Dumper;
my $codeLevel = q{6.1.0.7 (build 25.3.1103030000)};
print STDERR qq{$codeLevel\n};
my $vrmf;
if($codeLevel =~ /^\s*([0-9.]*) \(build.*\)/) {
$vrmf = version->parse($1);
}
print STDERR Dumper($vrmf);
The output becomes:
6.1.0.7 (build 25.3.1103030000)
$VAR1 = bless( {
'original' => '0',
'version' => [
0
]
}, 'version' );
I can’t find any documentation that says that print can affect variables passed to it, or that it affects the regex matching variables.
Can someone explain to me what is happening here, please?
Scalar values in Perl can be a number and a string at the same time. An SV object (SV = Scalar Value) has slots for integer, float, and string values and flags identifying which of those values are valid at any point in time. When you use a value as a string perl calculates the string value and sets a flag identifying it as valid. (Other operations, like adding 1 would invalidate the string value.) When you print something you’re (unsurprisingly) using it as a string. You can see this using Devel::Peek.
The result is
Note that in the second dump output the PV slot (string value) has been populated and the pPOK flag has been added under FLAGS.
So, yes,
printhas side-effects of a sort although under normal circumstances you should never notice.version->parse()appears to expect a string argument but isn’t triggering string semantics. Given thatversionprefers to use an XS implementation, it’s probably a bug there rather than in perl. Note that making a copy of the capture data causes the problem to disappear:Result: