Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Create a hash from an array

If I have the following array

my @header_line = ('id', 'name', 'age');

How do I create a hash from it equivalent to the line below?

my %fields = { id => 0, name => 1, age => 2};

The reason I want to do this is so that I can use meaningful names rather than magic numbers for indexes. For example:

$row->[$fields{age}]; # rather than $row->[2] 
like image 559
FunLovinCoder Avatar asked Nov 29 '22 04:11

FunLovinCoder


1 Answers

my %fields;
@fields{@header_line} = (0 .. $#header_line);
like image 134
Roman Cheplyaka Avatar answered Nov 30 '22 17:11

Roman Cheplyaka