I came across some unexpected behaviour and I'd be very grateful for any insight as to why this happens.
The odd behaviour is illustrated by the following minimal case:
use strict;
use warnings;
my $tainted = shift;
my $test;
$test = undef;
$test += $tainted;
print "Test 1: $test\n";
$test = undef;
$test += $tainted;
print "Test 2: $test\n";
This must be run with taint checking on in order to see the issue, so for this example, save as test.pl and run as follows with a numeric argument passed in, eg:
perl -T test.pl 1
Now, as I understand it, a '+=' op is allowed on an undefined value, so I'd expect this to work fine and to leave $test with a value of 1 in each case.
However, the surprising thing is, this triggers a warning because $test is undefined, but
ONLY the second time round after it has first been set with a tainted value and then undefined. So here's what happens:
%perl -T test.pl 1
Test 1: 1
Use of uninitialized value in addition (+) at test.pl line 12.
Test 2: 1
I tested this on 2 different Perls, both with same result:
- This is perl, v5.8.7 built for MSWin32-x86-multi-thread
- This is perl, v5.8.8 built for i386-freebsd
It's easy to workaround (eg. don't undef the variable, or if it needs resetting, set it to zero) but I am curious as to why this happens? Anybody got a good explanation for this?