Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficiently create a perl hash of consecutive numbers?

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?

like image 507
Bromide Avatar asked Dec 01 '22 07:12

Bromide


1 Answers

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.

like image 74
TLP Avatar answered Dec 05 '22 05:12

TLP