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

Why would the following happen:

%mapp = (); @arr = ("R", "T", "HH", "M"); $mapp{"FirstKey"} = \@arr; @val = $mapp{"FirstKey"}; print join (",", @{$mapp{"FirstKey"}}) . "\n"; #The array will be pr +inted push(@val, "RBB"); $mapp{"FirstKey"} = \@val; print join (",", @{$mapp{"FirstKey"}}) . "\n"; #an array reference wi +ll be printed

Output

R,T,HH,M ARRAY(0x7ffafc013bf8),RBB
How to solve this issue and print the new array instead of its reference?

Replies are listed 'Best First'.
Re: Map a string to an array
by runrig (Abbot) on Nov 01, 2013 at 22:36 UTC
    @val = $mapp{"FirstKey"};
    This assigns a reference to @arr to $val[0], because $mapp{FirstKey} contains a reference to the array @arr. When you stringify the reference, you get something like "ARRAY(0x7ffafc013bf8)". If you wanted to make @val a copy of @arr, then you can:
    @val = @{$mapp{FirstKey}};

      What would be the case if this is a 2d array? i.e, the map is from a string to 2d array.

      Is there an easy way to print the content?

        Not sure what you're asking. Do you want to make a copy of a 2D array? Or if you don't really need a copy, can you just use the reference.
        my @arr = ( [1,2], [3,4], ); my %hash = ( FirstKey => \@arr ); my $aref = $hash{FirstKey}; my $row0 = $aref->[0]; push @$row0, 99; use Data::Dumper; print Dumper \%hash;

        Further to runrig's replies:
        It's important to understand at each step how the structures of the hash and arrays are changing and evolving. Here's a kind of "running commentary" on that evolution, and a possible way to access and print what you want. Liberal use of data structure (for that's what you're dealing with; see perldsc) dump statements can be very enlightening about the changes that are going on. (And BTW, congratulations on being able to work with a system having at least 128 Terabytes of system RAM — or do I misinterpret the reference address of 0x7ffafc013bf8?)

        >perl -wMstrict -MData::Dump -le "my %mapp; my @arr = qw(R T HH M); ;; $mapp{k} = \@arr; my @val = $mapp{k}; ;; dd \%mapp; dd \@val; ;; print join q{,}, @{$mapp{k}}; ;; push @val, 'RBB'; dd \@val; ;; $mapp{k} = \@val; dd \%mapp; ;; print join q{,}, @{$mapp{k}}; print join q{,}, @{ $mapp{k}->[0] }, $mapp{k}->[1]; " { k => ["R", "T", "HH", "M"] } [["R", "T", "HH", "M"]] R,T,HH,M [["R", "T", "HH", "M"], "RBB"] { k => [["R", "T", "HH", "M"], "RBB"] } ARRAY(0x1e14b3c),RBB R,T,HH,M,RBB