Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

nested hash of array reference 1

Status
Not open for further replies.

margarmo

Programmer
Nov 8, 2006
2
US
Hi,
I am really having problems trying to put a new item into a hash of an array and passing it by reference I am afraid my code is way off the mark can someone please help me with it?

Thanks,
margamo


This is my code:

#!usr/bin/perl

use strict;
my $groceryStore = {
"fruits" => {
items => [ qw(perl plum apple) ],
bin => {
ailse => "1",
section => "B"
}
};

$newFruit = 'orange';
newProduce(%items, $newFruit);
sub newProduce { # given produce type, and item name, add to items
my (%$rh_items, $fruit) = @_;
push (%$rh_items, $fruit);

}
 
yes, your code is a bit off. the push() function is used to add things to an array, not a hash, so your line here is not correct:

Code:
push (%$rh_items, $fruit);

I'm not sure what you think %items is supposed to do in this next line:

Code:
newProduce(%items, $newFruit);

but even if %items was a valid hash you should rarely pass mixed data like that to a function. Besides you don't need to since your primary hash is already a reference to a hash: $groceryStore. To me that sort of confuses your code but it's perfectly valid. Anyway, assuming "orange" should end up in the array of fruits, here is your code corrected:

Code:
use strict;
use Data::Dumper;
my $groceryStore = {
   "fruits" => {
      items => [ qw(perl plum apple) ],
      bin => {
         ailse => "1",
         section => "B"
      }
   }
};

my $newFruit = 'orange';

newProduce($groceryStore, $newFruit);

sub newProduce {
  my ($hash_ref, $fruit) = @_;
  push @{ $hash_ref->{fruits}->{items} },$fruit;
}
print Dumper \$groceryStore;

the Data::Dumper module is a great tool for checking complex data structures. it will visually help you see how your data is structured and assist in debugging your code.

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top