I need to create something like this:
my $valueref = {
1 => 1,
2 => 2,
3 => 3,
4 => 4
};
Based on certain conditions, it might be up to 40, or 50 or 60. In each case it would be consecutive integers, as show in the example. Once created, it would never be changed, simply passed to a preexisting subroutine. Since both the keys and the values will be consecutive, I could also create the hash using a for
loop. I was curious what would be the fastest and/or most efficient way to create the hash? Or if there was yet another way it could be done?
Using map would suffice:
my $valueref = { map { $_ => $_ } 1 .. 40 };
Though one might note here that this is actually an array...
my @array = 0 .. 40;
So $valueref->{$n}
is actually $array[$n]
. I don't know if there is any benefit to using a hash in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With