Thursday, April 10, 2008

It's just a simple IF statement.. isn't it?

Okay here we come again with a weird problem I encountered today using perl. Take the following code:

#!/usr/local/bin/perl

use strict;
use warnings;

use Data::Dumper;

my $myvar;

print Dumper($myvar);

if ($myvar->{bleh}) {
$myvar->{bleh} = 'cool';
}

print Dumper($myvar);
So the value of 'myvar' should stay the same, whatever it is, from the first dump to the second dump right? Wrong!

Since the variable 'myvar' is not initialized, when you use it as a hash reference, Perl thinks this variable is a hash reference, and converts it to a hash reference! Here's the output of the above code:

$VAR1 = undef;
$VAR1 = {};
The value of this variable has clearly changed without notifying the programmer! Remember to always initialize your variables!

For this experiment I was using:

This is perl, v5.8.8 built for x86_64-linux-thread-multi

No comments: