6

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.
 }
mysteriousboy
  • 159
  • 1
  • 7
  • 20

2 Answers2

14

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);
Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • I have used both string and warnings. And I have initialize and define my_hash as well. I want to push the whole hash into new array. Thanks anyway. – mysteriousboy Mar 19 '13 at 21:11
  • 1
    @mysteriousboy You have already pushed the hashes into `@modifymyhash`. What's wrong with that? – Olaf Dietsche Mar 19 '13 at 21:16
2

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] };
choroba
  • 231,213
  • 25
  • 204
  • 289