Thursday, April 10, 2008

Damn you post conditional statements!

Consider the following code:



sub my_sub {

my %args = @_;

my $first_param = $args{first} if ($args{first});

print Dumper($first_param);

return 0;

}
So this code might seem all fine and work with no problem. But imagine the following scenario:
my_sub(first=>'hello');
my_sub();
What's the expected behavior? You would think that in the first call you would get a dump of 'hello' and in the second call get a dump of... of? undef? ''? Now this is what you get when you run the code:

$VAR1 = 'hello';
$VAR1 = 'hello';
Explanation:

So when the subroutine is called for the first time, the 'first' argument is defined, and the 'first_param' gets set to its expected value and there are no problems encountered. The 'first_param' variable's scope is just within the subroutine and it should get destroyed and blanked out when the method returns. But when the second time the subroutine is called, since the 'my' keyword is there, the 'first_param' is defined, but since the post conditional if() statement is false, the variable 'first_param' does not get set to undef or blank, instead it gets set to what that value was the last time the method was called!

I'm suspecting that Perl allocates the exact same memory location for the first_param variable the second time, and since it never gets initialized, it'll remain as what it was before!

Have a good day folks!



For this experiment I was using:

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

No comments: