Complex return value

Tkil tkil at
Tue Jun 4 18:05:51 CDT 2002

>>>>> "JW" == Jason White <jasona at> writes:

JW> I have a happy and well functioning hash of arrays in a
JW> subroutine.  If I return that hash to the main program, there's
JW> nothing useful inside.

How are you returning it?  How are you grabbing the return value?
Your phrase "nothing useful inside" makes me think you are trying to
return it in list context, but are trying to assign it to a scalar.
In that case, the scalar will most likely end up with 2x the number of
keys in the hash (or maybe the bucket statistics -- I don't remember

The basic idea is to return it the same way you try to catch it.  So,
these two are both "right" ways of doing it, with the latter being
more efficient for large hashes:

| sub return_hash_as_list { my %h = qw(a b c d); return %h; }
| my %hash = return_hash_as_list();
| sub return_hash_as_ref { my %h = qw(a b c d); return \%h; }
| my $href = return_hash_as_ref();

With the same two definitions, these are the wrong ways to do it:

| my %broken_hash = return_hash_as_ref(); # exception, odd num of vals in hash
| my $borken_href = return_hash_as_list(); # value is "2/8", not an href

JW> I've also tried passing a pointer to the global hash I want the
JW> data in and filling the data into that which didn't seem to work,
JW> although I don't usually use pointers, so I could have been doing
JW> that wrong.

If you mean "reference" and not pointer, than that should work (unless
you're masking it with a "my" or similar -- this is all under "use
strict" and "-w", isn't it?).  If we do:

| sub fill_href { my $href = shift; $href->{a} = "b"; $href->{c} = "d"; }

Then you can use it like this:

| my %hash = ( e => "f" );
| print join ", ", map "$_ => $hash{$_}", keys %hash;
| fill_href \%hash;
| print join ", ", map "$_ => $hash{$_}", keys %hash;

And get:

| e => f
| e => f, a => b, c => d

JW> What's the best way to get a hash of arrays back into a hash in my
JW> main function?

There's rarely any one good definition of "best".  Other than making
sure you really spawn off references to new arrays for each value, any
of the above techniques (that are supposed to work!) should work.


More information about the Pdx-pm-list mailing list