http://www.perlmonks.org?node_id=333077


in reply to Returning two hashes from a sub?

There is a technique mentioned in perlsub for dealing with this. Although it may be seen as old-fashioned, it still works fine, and allows you to deal with "real hash" syntax inside and outside the sub without resorting to global vars or en masse copying of data.

#! perl -sw use strict; sub getRefs{ my( %h1, %h2 ); @h1{ qw[the quick brown fox] } = (1..4); @h2{ 'a'..'z' } = 1 .. 26; return \%h1, \%h2; } { our( %glob1, %glob2 ); local( *glob1, *glob2 ) = getRefs(); print "$_ $glob1{ $_ }\n" for keys %glob1; print "$_ $glob2{ $_ }\n" for keys %glob2; } __DATA__ the 1 fox 4 brown 3 quick 2 w 23 r 18 a 1 x 24 d 4 j 10 y 25 u 21 k 11 h 8 g 7 f 6 t 20 i 9 e 5 n 14 v 22 m 13 s 19 l 12 c 3 p 16 q 17 b 2 z 26 o 15

What you do is assign the returned hashref to (localised) glob. You can then access the has via that glob name using standard hash variable syntax instead hashref syntax. It does simplify the syntax without the need to copy and avoiding the risks of global vars.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail