首页 > 解决方案 > 如何将 CSV 文件加载到 perl 哈希中并访问每个元素

问题描述

我有一个 CSV 文件,其中包含以逗号分隔的以下信息...

Owner,Running,Passing,Failing,Model
D42,21,54,543,Yes
T43,54,76,75,No
Y65,76,43,765,Yes

我想打开这个 CSV 文件并将其包含在我的程序中的 perl 哈希中。我也对在 has 中打印特定元素所需的代码感兴趣。例如,我将如何打印“所有者”Y65 的“通过”计数。

我目前拥有的代码:

$file = "path/to/file";

open $f, '<', $files, or die "cant open $file"

while (my $line = <$f>) {

#inside here I am trying to take the containments of this file and place it into a hash. I have tried numerous ways of trying this but none have seemed to work. I am leaving this blank because I do not want to bog down the visibility of my code for those who are kind enough to help and take a look. Thanks.

}

除了将 csv 文件放在散列中外,我还需要了解打印和浏览特定元素的语法。非常感谢您提前。

标签: fileperlcsv

解决方案


这是一个如何将数据放入哈希中的示例,%owners然后(在读取文件之后)为特定所有者提取“通过计数”。我正在使用该Text::CSV模块来解析文件的行。

use feature qw(say);
use open qw(:std :utf8);  # Assume UTF-8 files and terminal output
use strict;
use warnings qw(FATAL utf8);
use Text::CSV;

my $csv = Text::CSV->new ( )
  or die "Cannot use CSV: " . Text::CSV->error_diag ();
my $fn = 'test.csv';
open my $fh, "<", $fn
  or die "Could not open file '$fn': $!";
my %owners;
my $header = $csv->getline( $fh );  # TODO: add error checking 
while ( my $row = $csv->getline( $fh ) ) {
    next if @$row == 0; # TODO: more error checking
    my ($owner, @values) = @$row;
    $owners{$owner} = \@values;
}
close $fh;

my $key = 'Y65';
my $index = 1;
say "Passing count for $key = ", $owners{$key}->[$index];

推荐阅读