Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

In the following script the information is getting to the two print statements, but alas not into the hash. Could someone tell me what I'm doing wrong? Thanks
foreach $address (@dbs) { open (DAT,"< $memberinfo/$address"); @dbase_array = <DAT>; print "dbase_array = @dbase_array<br>"; print "address=$address<br>"; close(DAT); %unsubscribe = ($address => @dbase_array,); print "hash = %unsubscribe<br>"; } }

Replies are listed 'Best First'.
Re: passing information into a hash
by jeffa (Bishop) on Sep 29, 2003 at 14:04 UTC
    I think you want something like:
    $unsubscribe{$address} = [@dbase_array];
    Also, you really out to check out Data::Dumper for quick and dirty printing out of datastructures:
    use Data::Dumper; use CGI qw(:standard); my %unsubscribe; foreach my $address (@dbs) { open (DAT,'<',"$memberinfo/$address") or die "can't open $address: +$!\n"; my @dbase_array = <DAT>; print pre("dbase_array = ", Dumper \@dbase_array); print "address = $address", br(); close(DAT); $unsubscribe{$address} = [@dbase_array]; print pre("hash = ", Dumper \%unsubscribe); }
    And don't forget to use strict and warnings as well.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      I have a question about this line
      $unsubscribe{$address} = [@dbase_array];
      I guess I'm wondering if that is the same as this:
      $unsubscribe{$address} = \@dbase_array;
      technically?? Both create a reference to the array, but do they both accomplish the same exact thing? Or are they somehow different?
        Good question. :) For this particular case, i probably should have used your second snippet (take a reference to the array instead of copying it into a new anonymous one). Consider these:
        use Data::Dumper; my @array = qw(foo bar baz); my %hash; for (1..5) { my @array = qw(foo bar baz); $hash{$_} = \@array; undef @array; } print Dumper \%hash; for (1..5) { my @array = qw(foo bar baz); $hash{$_} = [@array]; undef @array; } print Dumper \%hash;
        I usually stick with an explicit copy since it tends to keep me out of trouble, but there are times when you do want to take a reference, and you just have to be careful when you do.

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)
        
      That worked perfectly, and I thank you for it.