How to access hash array in perl?

I have a large array of hashes, I want to grab the hash from the array and insert into a new array without changing the first array. I have a problem with a hash for an 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.
 }
+5
source share
2 answers

You must first

use strict;
use warnings;

then define

my $my_hash;

initialize $my_hashbefore assigning values, because otherwise you overwrite it and all three elements point to the same hash

$my_hash = {};

and finally to access the hash elements

$myarray[$i]->{firstname}

or print the entire hash, you can use Data :: Dumper , for example

print Dumper($myarray[$i])."\n";

- Perl? - Perl?

:

push (@modifymyhash, $myarray[$i]);

, .

foreach my $h (@myarray) {
    print Dumper($h), "\n";
}

foreach my $h (@modifymyhash) {
    print Dumper($h), "\n";
}

.

, , ith . @modifymyhash

my $copy = {};
%{$copy} = %{$myarray[$i]};
push (@modifymyhash, $copy);
+12

, %{ ... }:

print  %{ $myarray[$i] }, "\n";

, , , . , , "" :

print $_, ':', $myarray[$i]{$_}, "\n" for keys %{ $myarray[$i] };
+2

All Articles