Re: looping over an array of hashes



Graeme McLaren wrote:
Hi all, I need to loop over an array of hashes and assign a new hashref if a
condition is met:

I have a scalar which contains an array of hashes:

C:\tmp>cat -n tmp.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use Data::Dumper;
7
8 my $locations = [
9 { 'location_name' => 'Fionas House',
10 'location_id' => '9999000000000027',
11 },
12 { 'location_name' => 'Central Locations',
13 'location_id' => '9999'
14 },
15 { 'location_name' => 'The Queen\'s Hoose',
16 'location_id' => '1076'
17 },
18 { 'location_name' => 'Santa',
19 'location_id' => '1075'
20 },
21 ];
22
23 my %x = map { $_ => 1 } qw{ 9999000000000027 1075 };
24
25 for my $location ( @$locations ) {
26 $location->{location_status} = 1
27 if $x{ $location->{location_id} };
28 }
29
30 print Dumper $locations;

C:\tmp>tmp.pl
$VAR1 = [
{
'location_status' => 1,
'location_id' => '9999000000000027',
'location_name' => 'Fionas House'
},
{
'location_id' => '9999',
'location_name' => 'Central Locations'
},
{
'location_id' => '1076',
'location_name' => 'The Queen\'s Hoose'
},
{
'location_status' => 1,
'location_id' => '1075',
'location_name' => 'Santa'
}
];

HTH,
-jp

.



Relevant Pages

  • Re: Parsing a text file.....
    ... >>I guess using hashes is a way to go. ... >use warnings; ... >use strict; ... but the original post seemed to want the output lines in the ...
    (comp.lang.perl.misc)
  • RE: Hash of hashes?
    ... Subject: Hash of hashes? ... use strict; ... use warnings; ... One of the keys to my uderstanding of this is the use of %. ...
    (perl.beginners)
  • Explicit return and anonymous hashes
    ... I'm trying to merge two lists of hashes into one list of ... pgp@tui:~/tmp$ cat bar.pl ... use strict; ... use warnings; ...
    (perl.beginners)