Perl: Create a hash from an array

谁说胖子不能爱 提交于 2019-12-22 10:35:18

问题


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] 

回答1:


my %fields;
@fields{@header_line} = (0 .. $#header_line);



回答2:


my %fields = map { $header_line[$_] => $_ } 0..$#header_line;



回答3:


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' };




回答4:


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



回答5:


TIMTOWTDI

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


来源:https://stackoverflow.com/questions/4156483/perl-create-a-hash-from-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!