• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 341
  • Last Modified:

How to create array of hash ref.?

I want to create the array of hash reference at run time.
my @in = (1,2,3,4);
my @a;
my $b;
for my $in (@in) {
    $b->{id} = $in;
    push @a,  $b;
}
I would expect
@a= (  { id  =>  1 },
            { id  => 2 },
            { id  => 3 },
            { id => 4 },
          )
but  I have
@a = ( { id  =>4 },
            $a[0],
            $a[0],
            $a[0]
         ).
instead.
What is wrong? Please help!
Thanks.
Hanqian
0
Hanqian
Asked:
Hanqian
  • 3
2 Solutions
 
FishMongerCommented:
use Data::Dumper;

my @in = (1,2,3,4);
my @a;

for my $in (@in) {
    my $b = { id => $in };
    push @a,  $b;
}

print Dumper \@a;
0
 
clockwatcherCommented:
You're pushing a reference.  You'd need to create a copy to get what you're after.

use Data::Dumper;
my @in = (1,2,3,4);
my @a;
my $b;
for my $in (@in) {
    $b->{id} = $in;
    push @a,  {%$b};
}

print Dumper(@a);
0
 
FishMongerCommented:
You can also do it without $b

for my $in (@in) {
    push @a,  { id => $in };
}
0
 
FishMongerCommented:
For completeness, I thought I'd show you how to do this in 1 line by using map

use Data::Dumper;

my @a = map { {id => $_} } 1..4;

print Dumper \@a;
0
 
HanqianAuthor Commented:
FishMonger,

Thank you very much for giving me multiple method for this question! I really appreciate it.

Hanqian
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now