0

我有员工 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]
      ]

但是当我尝试打印每一行时,它每次都显示不同的行哈希

4

2 回答 2

3

问题是您使用的是单个 hash %row,所以\%row总是指同一个 hash。每次分配给 时%row,您都不会将其设置为新的哈希值,而只是清除相同的哈希值并重新填充它(从而间接影响数组的每个元素)。

要解决此问题,您需要在每次循环迭代中创建一个新哈希。对代码的最小更改是%row使用运算符声明为具有局部范围的词法变量my

        my %row = map { $_ => shift @columnValues } @columnNames;
        push @$hash, \%row;

另一种选择是完全消除中间变量,并在每次传递时生成对新匿名哈希的引用:

        push @$hash, { map { $_ => shift @columnValues } @columnNames };
于 2013-07-07T05:05:47.957 回答
0

如果您无法使 amap正常工作,请改用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;
于 2013-07-07T12:40:15.167 回答