Pass hash to a subroutine

N

Nick Li

Hi,

I would like to know how to pass a hash to a subroutine, which
evaluates its values and return a value.

Thanks in advance.

Nick
 
J

Jürgen Exner

Nick said:
I would like to know how to pass a hash to a subroutine, which
evaluates its values and return a value.

Hmmmm, just do it.
Where is the problem? I.e. show us your code or actually a minimal sample
program that exhibits your problem.
You read "perldoc perlsub", didn't you?

jue
 
A

Andy Baxter

At earth time Mon, 29 Dec 2003 06:53:09 -0800, the following transmission
was received from the entity known as Nick Li:
Hi,

I would like to know how to pass a hash to a subroutine, which
evaluates its values and return a value.

Thanks in advance.

Nick

One way is to pass a reference to the hash. The reference is a scalar, so
you can pass it along with other parameters including other hash and array
refs without them getting mixed up. e.g.

my %hash=(key1=>"whatever",
key2=>"something else",
);

$catvals=CatVals(\%hash,"="," ");

print $catvals;
exit;

sub CatVals {
my ($pHash,$eq,$cat)=@_;
@keys=keys(%$pHash);
my ($key,$str);
foreach $key (@keys) {
$str.=$key.$eq.$$pHash{$key}.$cat;
};
$str;
};

outputs:

bash-2.05b$ ./test.pl
key2=something else, key1=whatever,

ALternatively, do 'perldoc -q hash', and look for the section that starts:

Found in /usr/share/perl/5.8.2/pod/perlfaq7.pod
How can I pass/return a {Function, FileHandle, Array, Hash, Method,
Regex}?

With the exception of regexes, you need to pass references to these
objects. See "Pass by Reference" in perlsub for this particular ques-
tion, and perlref for information on references.

andy.
 
W

Web Surfer

[This followup was posted to comp.lang.perl.misc]

ningli2000 said:
Hi,

I would like to know how to pass a hash to a subroutine, which
evaluates its values and return a value.

Thanks in advance.

Nick

In the example below I have passed the hash by reference.
When you "pass by value" Perl copies all the values of the hash onto the
stack before it calls the subroutine (which can use up a lot of time if
the hash is large) as opposed to "pass by reference" which just passes a
"reference" to the hash top the subroutine (kind of like passing the
address). The only "drawback" of passing by reference is that you can
modify the contents of the hash.

$status = &process(\%myhash);


sub process
{
my ( $hash_ref ) = @_;
my ( $key );

foreach $key ( keys %$hash_ref ) {
}

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top