Reputation: 159
I have a big array of hashes, I want to grab some hash from the array and insert into new array without changing the first array. I am having problem pushing the hash to array, how do I access the ith element which is a hash.
my @myarray;
$my_hash->{firstname} = "firstname";
$my_hash->{lastname} = "lastname";
$my_hash->{age} = "25";
$my_hash->{location} = "WI";
push @myarray,$my_hash;
$my_hash->{firstname} = "Lily";
$my_hash->{lastname} = "Bily";
$my_hash->{age} = "22";
$my_hash->{location} = "CA";
push @myarray,$my_hash;
$my_hash->{firstname} = "something";
$my_hash->{lastname} = "otherthing";
$my_hash->{age} = "22";
$my_hash->{location} = "NY";
push @myarray,$my_hash;
my @modifymyhash;
for (my $i=0;$i<2; $i++) {
print "No ".$i."\n";
push (@modifymyhash, $myarray[$i]);
print "".$myarray[$i]."\n"; #How do I print first ith element of array which is hash.
}
Upvotes: 6
Views: 27190
Reputation: 74028
First you should
use strict;
use warnings;
then define
my $my_hash;
initialize $my_hash
before you assign values, because otherwise you overwrite it and all three elements point to the same hash
$my_hash = {};
and finally, to access the hash's members
$myarray[$i]->{firstname}
or to print the whole hash, you can use Data::Dumper for example
print Dumper($myarray[$i])."\n";
or some other method, How can I print the contents of a hash in Perl? or How do I print a hash structure in Perl?
Update to your comment:
You copy the hashes with
push (@modifymyhash, $myarray[$i]);
into the new array, which works perfectly. You can verify with
foreach my $h (@myarray) {
print Dumper($h), "\n";
}
foreach my $h (@modifymyhash) {
print Dumper($h), "\n";
}
that both arrays have the same hashes.
If you want to make a deep copy, instead of just the references, you can allocate a new hash and copy the ith
element into the copy. Then store the copy in @modifymyhash
my $copy = {};
%{$copy} = %{$myarray[$i]};
push (@modifymyhash, $copy);
Upvotes: 14
Reputation: 241868
To dereference a hash, use %{ ... }
:
print %{ $myarray[$i] }, "\n";
This probably still does not do what you want. To print a hash nicely, you have to iterate over it, there is no "nice" stringification:
print $_, ':', $myarray[$i]{$_}, "\n" for keys %{ $myarray[$i] };
Upvotes: 2