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.
 }

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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 You have already pushed the hashes into @modifymyhash. What's wrong with that?
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] };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.