【问题标题】:How to code a complex array of hashes in Perl?如何在 Perl 中编写复杂的哈希数组?
【发布时间】:2017-08-12 13:08:06
【问题描述】:

这是一个让我困惑了很长时间的任务: 我们通常会以 .csv 文件的形式获取学生的考试结果。标题包含一些元数据,例如 ID、性别、出生日期、状态、考场、座位号、考试版本以及 60 道问题的分数(如果答案错误、半正确或正确,则为 0.0 0.5 1.0 分) )。考试有 6 个版本 (A - F),仅按 60 个问题的顺序不同。存储信息用于统计评估,这需要根据考试主文件进行正确对齐(一个 .txt 文件,版本 A-F 有 7 列,第 7 列中有正确答案)。 我尝试将 .csv 文件作为哈希数组来生成不同的 .csv 或选项卡式 .txt 文件,其中所有考试结果以统一的顺序显示,以供以后进行统计评估。

示例: 标题—— ID,性别,生日,订单,房间,座位,版本,积分,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,

277710814533,f,01/02/1993,m,sr_3,A11,A, 1,1,1,1,0,1,1,1,.5,1,1,1,0,1, .5,1,1,1,0,1,.5,1,1,0,1,1,1,1,1,1,1,0,0,1,0,1,.5,1 ,1,1,1,.5,0,1,1,1,0,1,1,1,1,1,0,1,1,1,.5,1,1,1

755310765962,f,31/07/1992 00:00,v,aula,C11,C,1,.5,0,1,1,1,1,1,1,1,1,1,1 ,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,.5,1,0,.5,1,0,1,. 5,0,.5,0,1,0,0,.5,1,1,0,.5,1,1,.5,.5,1,.5,.5,1,1,1 ,.5,.5

394610513538,m,20/10/1992 00:00,m,sr_3,E13,E,1,1,0,.5,1,1,1,1,1,1,1,.5, 1,1,.5,.5,1,1,1,.5,.5,1,1,1,1,0,0,.5,1,1,.5,.5,.5, .5,0,1,0,.5,0,0,1,0,1,.5,0,1,0,0,.5,1,0,1,1,0,.5,. 5,.5,.5,.5,.5

代码根据以下方案生成哈希键:

while ( <FH> ) {
chomp ;
if ( /^\d\d\d/) {
    ( $id , $gender , $birthday , $status , $room , $seat , $version , @points ) = split ( /,/ , $_ ) ;
    $student = { 
        'id'       => $id ,
        'gender'   => $gender , 
        'birthday' => $birthday ,
        'position' => $position ,
        'room'     => $room , 
        'seat'     => $seat ,
        'version'  => $version ,
        'points'   => @points
    } ;
    push ( @candidates , $student ) ;
}
} ;
close FH ;
print "Number of candidates processed: " . ( $#candidates + 1 ) . "\n" ;

编译器会为每条记录抛出一个警告,例如“/Documents//testAoH.pl 第 38 行,第 16 行的匿名哈希中的奇数个元素。”但脚本已执行。

脚本打印正确数量的已处理记录,但是当我尝试检索特定记录时,我只得到标量值,@points 数组只产生一个(第一个?)结果,就好像它被破坏了一样。数据转储器输出进一步表明此代码内部一定有问题。

数据转储器,例如

    755310765962 
$VAR1 = \{
        '0' => '0',
        'gender' => 'f',
        'id' => '755310765962',
        'points' => '1',
        'room' => 'aula',
        '.5' => undef,
        '1' => '.5',
        'birthday' => '31/07/1992',
        'seat' => 'A11',
        'version' => 'A',
        'status' => 'v'
      };

有什么线索吗?

谢谢-哈拉尔-

【问题讨论】:

    标签: arrays csv hash perl-data-structures


    【解决方案1】:

    使用 \@points。 @points 在散列构造函数中展开以生成: '点' => $points[0], $points[1] => $points[2], ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 2011-09-29
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多