> -----Original Message-----
> From: Jennifer Pan [mailto:[EMAIL PROTECTED]]
> Sent: Thursday, August 23, 2001 1:05 PM
> To: [EMAIL PROTECTED]
> Cc: Maxim Berlin
> Subject: hash of ref to array of arrays, lost all but the last element
> in hash
> 
> 
> Dear all, 
> 
> I would like to construct a hash, whose value holds a reference to an
> array of arrays,
> however all the keys in my hash have the exact same value, which turns
> out to be the value of the last element I put it!!
> 
> I felt that something is wrong in the data structure, that I 
> should not
> keep re-using @match or @splice, they get overwritten, so I only came
> with the last one. But I am not sure how to fix it, or is there a way?
> 
> Any insight is much appreciated!!!
> 
> -Jennifer 
> 
> 
> #! /usr/bin/perl -w
> 
> my %hash;
> my $MatchLine;
> my $SVLine;
> 
> while (<STDIN>) {
>   chomp $_;
>   if (/^Query=(\w+)$/) {
> 
>     if ($key) {
>     
>     
>     @match = split (' ', $MatchLine);
>     @splice = split (' ', $SVLine);
>     
>     
>     
>     $ref = [\@match, \@splice];
>     
>     $hash{"$key"}= $ref;
>     $key = $1;
>     } else {
>   
>     $key =$1
>     }
>   } elsif (/^MA:(.+)$/) {
>     $MatchLine = $1;
>   } elsif (/^SV:(.+)$/) {
>     $SVLine = $1;
>   } else {
>   }
> }
> 
> 
> foreach $key (keys %hash) {
>       print "$key\n";
>       print "$_" for (@$mref);
>       print "\n";
>       print "$_" for (@$svref);
>       print "\n";
> }

You are correct that the line:

   $ref = [\@match, \@splice];

Is "reusing" those arrays.

Two ways around this:

1. Make the arrays lexically scoped inside the loop body. Even though
the names go out of scope, the arrays hang around since you still have
active references to them:

    my @match = split (' ', $MatchLine);
    my @splice = split (' ', $SVLine);

2. Make anonymous copies of the arrays:

   $ref = [ [ @match ], [ @splice ] ];

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to