passing hash and another arg to a sub

M

mike

hi

i have something like this
%names = (1=>['TEST','12345','testuser'],
2=>['TEST USER','12345','testuser1']);

do_something(%names,'ABC');


sub do_something {
my (%hash,$abc) = @_;
print "abc = $abc";

while ( my ($keys,$val) = each(%hash) )
{
print "key = $keys, value = $val\n";
}

}

i got the output
abc =
key = ABC, value =
key = 1, value = ARRAY(0x1abeff4)
key = 2, value = ARRAY(0x1abf0fc)


why does 'ABC' become a key inside the hash?? I think there's someting
wrong with passing the @_.
thanks for any help
 
G

Gunnar Hjalmarsson

mike said:
i have something like this
%names = (1=>['TEST','12345','testuser'],
2=>['TEST USER','12345','testuser1']);

do_something(%names,'ABC');

<snip>

You asked a FAQ.

perldoc -q pass/return
 
A

Alan Mead

hi

i have something like this
%names = (1=>['TEST','12345','testuser'],
2=>['TEST USER','12345','testuser1']);

do_something(%names,'ABC');


sub do_something {
my (%hash,$abc) = @_;
print "abc = $abc";

while ( my ($keys,$val) = each(%hash) )
{
print "key = $keys, value = $val\n";
}

}

You need to pass a reference to the hash:

do_something(\%names,'ABC');

....

sub do_something {
my($hash,$abc) = @_;

print join(', ',keys %$hash);
$$hash{'my new key'} = 'this will change %hash in the calling scope!';
...

There are some great documents related to references that come with perl.
Type 'man perl' and look for "reference". The data structures cookbook
is also thrilling reading.


-Alan
 
C

Chris Mattern

mike said:
hi

i have something like this
%names = (1=>['TEST','12345','testuser'],
2=>['TEST USER','12345','testuser1']);

do_something(%names,'ABC');


sub do_something {
my (%hash,$abc) = @_;

This assigns *all* of @_ to %hash. $abc
gets no value.
print "abc = $abc";

while ( my ($keys,$val) = each(%hash) )
{
print "key = $keys, value = $val\n";
}

}

i got the output
abc =
key = ABC, value =
key = 1, value = ARRAY(0x1abeff4)
key = 2, value = ARRAY(0x1abf0fc)


why does 'ABC' become a key inside the hash??

Because that's how the assignment you wrote works. If you're
passing a list through @_, it has to be the only list and it
has to be *last*, because it'll slurp all the remaining values
out of @_. Try it like this:

do_something('ABC', %names);

and

my ($abc, %hash) = @_;

I think there's someting
wrong with passing the @_.
thanks for any help

--
Christopher Mattern

"Which one you figure tracked us?"
"The ugly one, sir."
"...Could you be more specific?"
 

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

No members online now.

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top