in reply to Re^2: How to populate a HASH using a FOR loop to a FUNCTION
in thread How to populate a HASH using a FOR loop to a FUNCTION

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.