Talk:A Practical Perl Guide
From Gentoo Linux Wiki
You say here that functions can't return a hash but it's misleading: A function can't return an array, either. You said correctly that it can return a scalar or a list. A list can represent an array or a hash, all the same. Try
sub a { return 'a', 1, 'b', 2 }<br />
%hsh = a();<br />
print $hsh{'b'}, "\n" code>
and you get "2". So functions can return hashes just as they can return arrays - via lists.
~Sixtease <Sixtease@gmail.com>
Of course, there can be a question asked, how to return two separate arrays/hashes. Obviously, you can't. But instead, you can return single or multiple references, each one referring to respective array or hash. For example:
sub b { return [1,2,3], {a=>11, b=>22} } code>
Then such a function can be called as:
($list_ref, $hash_ref) = b(); code>
... and you're done, you have your array in @$list_ref and your hash in %$hash_ref. Notice the @$ and %$ notation. This is a simple dereference method for such case. A little better way is to write @{$list_ref} and %{$hash_ref} (this looks really ugly and is similar to some hax00r code), and you can get any stored values from the list or the hash by simply using $list_ref->[index] or $hash_ref->{key}. The only difference to normal arrays or hashes is that an arrow has to be placed right after the variable.
For examples its useful to teach people how to use the open() function in a secure way (calling it with 3 arguments). This will lead to less bad code in the long run. Also using single quotes when not quoting things that need to be interpreted.
