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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|