如何将CSV文件加载到perl哈希中并访问每个元素 [英] How to load a CSV file into a perl hash and access each element
问题描述
我有一个CSV文件,其中包含以下信息,并用逗号分隔...
I have a CSV file with the following information seperated by commas ...
Owner,Running,Passing,Failing,Model
D42,21,54,543,Yes
T43,54,76,75,No
Y65,76,43,765,Yes
我要打开此CSV文件,并将其包含在程序中的perl哈希中。我也对在has内打印特定元素所需的代码感兴趣。例如,我将如何打印所有者 Y65的通过计数。
I want to open this CSV file and place its containments inside of a perl hash in my program. I am also interested in the code needed to print a specific element inside of the has. For example, how I will print the "Passing" count for the "Owner" 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.
}
AS以及将csv文件放在散列中还需要了解打印和浏览特定元素的语法。
AS well as placing the csv file inside of a hash I also need to understand the syntax to print and navigate through specific elements. Thank you very much in advance.
推荐答案
这里是如何将数据放入哈希%owners
及更高版本(在读取文件后)为特定所有者提取通过计数。我正在使用 Text :: CSV
Here is an example of how to put the data into a hash %owners
and later (after having read the file) extract a "passing count" for a particular owner. I am using the Text::CSV
module to parse the lines of the file.
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];
这篇关于如何将CSV文件加载到perl哈希中并访问每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!