Perl: create a hash from an array

If I have the following array

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

How to create a hash from the equivalent of the line below?

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

The reason I want to do this is because I can use meaningful names, not magic numbers for indexes. For instance:

$row->[$fields{age}]; # rather than $row->[2] 
+3
source share
5 answers
my %fields;
@fields{@header_line} = (0 .. $#header_line);
+15
source
my %fields = map { $header_line[$_] => $_ } 0..$#header_line;
+6
source

, Text:: CSV. .

$csv->column_names( @header_line );
$row = $csv->getline_hr( $FH );
print $row->{ 'id' };

+2
my %fields = ();
for (my $i = 0; $i < scalar(@header_line); $i++) {
   $fields{$header_line[$i]} = $i;
}
+1

TIMTOWTDI

my %fields = ();
foreach my $field(@header_line)
{
  %fields{$field} = scalar(keys(%fields));
}
0

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


All Articles