我有员工CSV数据和我 尝试将每个员工哈希插入数组
open($empOutFh,">empOut.txt")
$hash= [];
while(<$empFh>) {
@columnNames = split /,/, $_ if $.==1;
@columnValues = split /,/, $_;
%row = map{$_=>shift @columnValues}@columnNames;
push @$hash,\%row;
}
print Dumper($hash);
我得到输出
$VAR1 = [
{
'emp_no' => '11000',
'hire_date
' => '1988-08-20
',
'birth_date' => '1960-09-12',
'gender' => 'M',
'last_name' => 'Bonifati',
'first_name' => 'Alain'
},
$VAR1->[0],
$VAR1->[0],
$VAR1->[0]
]
但是当我尝试打印每一行时,它每次显示不同的行哈希
答案 0 :(得分:3)
问题是您使用的是单个哈希%row
,因此\%row
始终引用相同的哈希值。每次分配给%row
时,你都没有将它设置为新的哈希,你只是清除相同的哈希并重新填充它(从而间接影响数组的每个元素)。
要解决此问题,您需要在每次循环迭代中创建一个新哈希。对代码的最小更改是使用%row
运算符将my
声明为具有局部作用域的词法变量:
my %row = map { $_ => shift @columnValues } @columnNames;
push @$hash, \%row;
另一种选择是完全消除中间变量,并在每次传递时生成对新的匿名哈希的引用:
push @$hash, { map { $_ => shift @columnValues } @columnNames };
答案 1 :(得分:0)
如果无法让map
正常工作,请改用foreach
循环。能够维护代码比聪明更重要。
#!/usr/bin/env perl
use strict;
use warnings;
# --------------------------------------
use Data::Dumper;
# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;
# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;
# --------------------------------------
# open($empOutFh,">empOut.txt")
my $emp_file = 'empOut.txt';
open my $emp_out_fh, '>', $emp_file or die "could not open $emp_file: $!\n";
# $hash= [];
my @emps = ();
my @columnNames = ();
# while(<$empFh>) {
while( my $line = <$empFh> ){
chomp;
# @columnNames = split /,/, $_ if $.==1;
if( $. == 1 ){
@columnNames = split /,/, $line;
next;
}
# @columnValues = split /,/, $_;
my @columnValues = split /,/, $line;
my %row = ();
# %row = map{$_=>shift @columnValues}@columnNames;
for my $i ( 0 .. $#columnNames ){
$row{$columnNames[$i]} = $columnValues[$i];
}
# push @$hash,\%row;
push @emps, \%row;
# }
}
# print Dumper($hash);
print Dumper \@emps;