> Functions should return their results through the return rather than through a reference.
Plz be aware that passing and returning hashes as lists can cause much useless overhead, if the original hash has to be overwritten.
Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
| [reply] |
Functions should return their results through the return rather than through a reference.
Hi Bill,
Yes, I agree in general and often try to write "pure" functions, but I am at the same time generally quite reluctant at the idea of passing around many times a data structure, because this is quite inefficient, as already pointed out by LanX. (Granted, it does not really matter with such small array and hash, but I am usually manipulating fairly large data structures.)
Anyway, I would not do it the way I described in my first code sample, which aimed at keeping the general code structure of the OP, which was passing a reference to the hash. BTW, this is not very useful here in view of the fact that the hash is in fact a global variable.
If I wanted to populate the hash in a separate function (which is not really needed in such a simple case, but I am often doing this type of thing when populating the hash is more complicated and requires, for example, to read from one or several file(s) and process the content before actually storing keys and values into the hash), I would call that function only once and pass to it a reference to the array and then return the hash or, when the data is large, return a reference to the hash. Something along these lines:
use strict;
use warnings;
use Data::Dumper;
my @array = qw( sean connery george lazemby roger moore timothy dalton
+ pierce brosnan );
my $hash_ref = populate_hash(\@array);
print Dumper $hash_ref;
sub populate_hash {
my $array_ref = shift;
my %hash;
for (0..4) {
my ($key, $val) = splice @$array_ref, 0, 2;
$hash{$key} = $val;
}
return \%hash;
}
But, again, this is only for the sake of argument: for such a simple case, I would not even use a separate function, and the easiest solution is the one provided by AnomalousMonk.
| [reply] [d/l] |
Dear Bill,
you are right: all the text I have used herein was just for debugging. The actual function I would like to create would just populate a given hash when called in different points within the main scripts. And at the moment I have no idea what Dumper is...
G
| [reply] |
| [reply] [d/l] |