If you were using strict, you wouldn't probably wouldn't be having this problem because you would have declared @array with my and made it lexically scoped. As it is, you're using a global variable, thus always pointing to the same reference. However, even lexically scoping the array isn't going to help because you're calling undef on the array that you're pointing to. The following should work. I replaced your for loop with a call to Data::Dumper to make it easier to see the results.
use strict;
use Data::Dumper;
my %cluster;
while (<DATA>) {
chomp;
my @ary = split;
my $user = shift @ary;
$cluster{$user} = \@ary;
}
print Dumper \%cluster;
__DATA__
bob's your uncle
Ovid is in da house
To get a little more specific, if you use a variable without declaring it (such as when you fail to use strict and my), the variable is automatically created as a global variable in the current namespace. For most programs, this means your variables with be in the main:: namespace. Your @ary is actually @main::ary. Every time you took a reference to it, it was the same array.
When you lexically scope a variable by declaring it with my, you create a new, private instance of that variable that has absolutely no relation to a global variable of the same name. For instance, these two instances of $foo are not the same:
#!/usr/bin/perl
$foo = "bar";
{
my $foo = "something else";
print "$foo\n";
}
print "$foo\n";
Behavior like this can introduce plenty of subtle bugs, if people are unaware of what's going on. By always using strict, you can avoid these bugs.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |