How to efficiently create perl hashes from sequential numbers?

I need to create something like this:

my $valueref = { 1 => 1, 2 => 2, 3 => 3, 4 => 4 }; 

Depending on certain conditions, this can be up to 40, or 50 or 60. In each case, these will be consecutive integers, as shown in the example. Having created it, it will never be changed, it is simply transferred to the existing subroutine. Since both keys and values ​​will be consecutive, I could also create a hash using a for loop. I was curious what would be the fastest and / or most efficient way to create a hash? Or, if there is another way, can this be done?

+4
source share
4 answers

Using a map would be enough:

 my $valueref = { map { $_ => $_ } 1 .. 40 }; 

Although you may notice 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.

+10
source

I would use map for this:

 my $highest_value = 50; my %foo = map { $_ => $_ } 1 .. $highest_value ; 

Remember that order is not guaranteed in a hash.

+5
source

"Once created, it will never be changed, just the pre-existing subroutine will be transferred"


Sounds like a good candidate for state keyword (or close):

 use feature 'state'; sub foo { my ( $param1, $param2, $limit ) = @_; state $valueref = { map { $_ => $_ } 0 .. $limit }; ... } 

This allows you to initialize the data structure, and then you do not have to worry about passing it as an argument later.

+5
source

Hash fragment? Something like that:

 my %hash; my $count = 10; @hash{1..$count} = (1..$count); 
0
source

Source: https://habr.com/ru/post/1388940/


All Articles