Perl: Create a hash from an array

2019-05-11 02:24发布

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] 

5条回答
Anthone
2楼-- · 2019-05-11 02:55
my %fields = ();
for (my $i = 0; $i < scalar(@header_line); $i++) {
   $fields{$header_line[$i]} = $i;
}
查看更多
▲ chillily
3楼-- · 2019-05-11 02:56
my %fields = map { $header_line[$_] => $_ } 0..$#header_line;
查看更多
聊天终结者
4楼-- · 2019-05-11 02:58

You said in reply to a comment that this is coming from Text::CSV. This module has a way to import this into a hash for you.

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

查看更多
We Are One
5楼-- · 2019-05-11 03:04

TIMTOWTDI

my %fields = ();
foreach my $field(@header_line)
{
  %fields{$field} = scalar(keys(%fields));
}
查看更多
▲ chillily
6楼-- · 2019-05-11 03:15
my %fields;
@fields{@header_line} = (0 .. $#header_line);
查看更多
登录 后发表回答