View previous topic :: View next topic |
Author |
Message |
wswartzendruber Veteran
Joined: 23 Mar 2004 Posts: 1261 Location: Idaho, USA
|
Posted: Sun Nov 22, 2009 12:55 am Post subject: Perl: Passing an Array of Hashes as a Parameter to a Sub |
|
|
I can't for the life of me figure out how to do this. _________________ Git has obsoleted SVN.
10mm Auto has obsoleted 45 ACP. |
|
Back to top |
|
|
gentoo_ram Guru
Joined: 25 Oct 2007 Posts: 474 Location: San Diego, California USA
|
Posted: Sun Nov 22, 2009 5:44 pm Post subject: |
|
|
The short answer is, you really can't. But you can pass an array of hash references. Then dereference the hash references in your sub.
Code: | # sub: dump the hash values with the keys '1' and '3'
sub dumpvals
{
foreach $h (@_)
{
print "1: $h->{1} 3: $h->{3}\n";
}
}
# initialize an array of anonymous hash references
@arr = ({1,2,3,4}, {1,7,3,8});
# create a new hash and add the reference to the array
%t = (1, 5, 3, 6);
push @arr, \%t;
# call the sub
dumpvals(@arr);
|
Output is:
Code: | > perl param.pl
1: 2 3: 4
1: 7 3: 8
1: 5 3: 6
|
|
|
Back to top |
|
|
wswartzendruber Veteran
Joined: 23 Mar 2004 Posts: 1261 Location: Idaho, USA
|
Posted: Sun Nov 22, 2009 6:36 pm Post subject: |
|
|
Thank you, sir. _________________ Git has obsoleted SVN.
10mm Auto has obsoleted 45 ACP. |
|
Back to top |
|
|
desultory Bodhisattva
Joined: 04 Nov 2005 Posts: 9410
|
Posted: Mon Nov 23, 2009 2:11 am Post subject: |
|
|
Are you sure that you want to pass an array (@foo) not an array reference(\@foo), or more safely a reference to a copy of the array (\[@foo])?
The perldsc, perlref and perlreftut man pages (or perdocs if you prefer) have more information should you need it. |
|
Back to top |
|
|
sundialsvc4 Guru
Joined: 10 Nov 2005 Posts: 436
|
Posted: Mon Nov 23, 2009 2:27 am Post subject: |
|
|
It's always "a hashref." Or, "an arrayref."
There is, as you may expect, "more than one way to write it." But in any case, you are passing a reference to an array|hash containing references to arrays|hashes. |
|
Back to top |
|
|
desultory Bodhisattva
Joined: 04 Nov 2005 Posts: 9410
|
Posted: Mon Nov 23, 2009 3:37 am Post subject: |
|
|
When you pass an array it is taken as, a slice of, the argument list, which has rather different implications than passing a reference to it. |
|
Back to top |
|
|
|