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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing an array of hashes to a subroutine

Status
Not open for further replies.

Loon

Programmer
May 24, 2000
100
GB
Hi

I am trying to pass a 2 element array (each element consisting of a hash with three fields, let's call them a, b & c...)

I pass to the func by reference, e.g.

Code:
&function(\@myArrayOfHashes);

I try referencing a variable to get hold of the array:

Code:
my $reference = shift;

But how do I now read off a hash element at a time?? I.e. I'd like to be able to do:

Code:
my %hashElement = pop @{$reference};

print "These are my hash values: ";
print $hashElement{'a'} .", ";
print $hashElement{'b'} .", ";
print $hashElement{'b'} .", ";

Doesn't work though.. I get the error:
Code:
Use of uninitialized value in concatenation (.)

I.e. $hashElement hasn't got any values/keys in it.. I suspect that my array of hashes is now just a list of strings (the keys and values having lost their meaning) - any way of getting round this?

Cheers
L00n

 
You have to coerce the returned value to be a hash using either:
Code:
my $ref = pop @array; my %hash = %$ref;
or:
Code:
my %hash = %{ pop @array };
A fuller example:
Code:
my @arrayOfHashes = (
  { a => 1, b => 2 },
  { A => 10, B => 20 },
);

sub doSomething {
  my $arrayOfHashesRef = shift;
  foreach $element (@{$arrayOfHashesRef}) {
    foreach (sort keys %{$element}) {
      print "$_ => $element->{$_}\n";
    }
  }
}

doSomething( \@arrayOfHashes );
Cheers, Neil :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top