Light Bringer
Light Bringer

Reputation: 829

Inexplicably a Perl local my(array) acts like a global variable, dirty on subsequent iterations

Simply want to know why the @b is acting like a global and has to be reset each time the subroutine is called. A my(variable) shouldn't last past the routine but this one is persistent. The first iteration works, but the subsequent ones would be corrupted without the for loop setting to 0.

Also, @b doesn't respond to a; Print Join(); @b=(0)x@$a; mapping; or any other calls to it, nothing besides a direct query of $b(#) and nothing else. Couldn't be the chink in the Perl armor, could it?

Yes, if I comment out the 1st iteration and the for loop, the 2nd iteration works but subsequent ones do not.

sub firstDupe {
    my ($a) = @_;
    my @b;
    # need for next line inexplicable, @b acts like global, ideas?
    my $l = scalar(@{$a})+1; for ($i=0; $i < $l; $i++){ $b{$i}='0'; }
    for (@{$a}){
        return int($_) if $b{$_}++;
    }
    return -1;
}

my @pb= (2, 1, 3, 5, 3, 2);
$val=&firstDupe(\@pb);
my $ret="\nRet: $val";

@pb= (2, 4, 3, 5, 1);
$val=&firstDupe(\@pb);
$ret = $ret.", $val";

@pb= (1);
$val=&firstDupe(\@pb);
$ret = $ret.", $val";

@pb= (2,2);
$val=&firstDupe(\@pb);
$ret = $ret.", $val";

@pb= (2,1);
$val=&firstDupe(\@pb);
$ret = $ret.", $val";

print "\n\n$ret";
print "\nkey: 3, -1, -1, 2, -1\n";

Upvotes: 4

Views: 134

Answers (1)

zdim
zdim

Reputation: 66881

This is because you have $b{$i} -- that is, a hash %b, which is never declared (made lexical).

So it is created, right there, as a global variable.

This would have not been possible with use strict; in place.

May I recommend to always, always use this pragma, and even more so use warnings;.


Note that $a and $b are not advisable for variable names, since those particular names have a bit special standing, being used by sort.

Also, you don't need that & in front of your functions. It has very specific properties, which don't hurt here, but it is not needed and it shouldn't be there.

Upvotes: 14

Related Questions