Re: looping over an array of hashes



On Fri, 2006-28-04 at 15:40 +0100, 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:

$locations = [
{
'location_name' => 'Fionas House',
'location_id' => '9999000000000027'
},
{
'location_name' => 'Central Locations',
'location_id' => '9999'
},
{
'location_name' => 'The Queen\'s Hoose',
'location_id' => '1076'
},
{
'location_name' => 'Santa',
'location_id' => '1075'
},
]



I want to add an new hash ref in if, for example,

if($x ==9999000000000027){
$locations->[0]->{'location_status'} = 'true'

}


I've been at this a few hours and I'm not getting anywhere, can anyone
suggest a way to do this?

An reference to an array can be dereferenced to an array:

for my $item ( @$locations ){ # $item references each hash in the list
if( $item->{location_id} == 9999000000000027 ){
$item->{location_status} = 'true';
}
}

--
__END__

Just my 0.00000002 million dollars worth,
--- Shawn

"For the things we have to learn before we can do them, we learn by doing them."
Aristotle

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/


.



Relevant Pages

  • Re: Counting keys in an array of hashes?
    ... I would like to sort the array based on the value of $data ... I am not proficient with hashes, so I apologize in advance for my ... This is a hash slice*. ...
    (perl.beginners)
  • Re: Question about multi-demension hash initialization
    ... On Sat, Sep 20, 2008 at 10:47 AM, Robert Klemme ... You know how to create nine hashes but you do not know how to ... For example, I have a multidimensional array, which I then take each ...
    (comp.lang.ruby)
  • Re: Parsing an Array of Hashes
    ... I am dealing with an array of hashes in my program. ... I need to either retain this hash or delete this hash from the array. ... I need to parse arrayOfAll, picking up each Hash turn by turn, and in ...
    (comp.lang.perl.misc)
  • Re: excessively verbose request for help with regex and arrays
    ... The part where you describe Arrays of Hashes is a bit confusing as well, can you describe your data structure using code rather than English? ... This doesn't check for multi-line strings, names with ':' in and other weirdness though. ... If you have an Array of text lines then you can just iterate through, scan each one and store the data in another Array: ...
    (comp.lang.ruby)
  • YAHP - Ref to a hash via xml::simple prob.
    ... I am trying to get to grips with a fragment of an XMLin structure ... Set=Array of Hashes ... and can work out what I want, but the array Ummmm. ... Dumping $m->shows ...
    (comp.lang.perl.misc)