file - 如何将 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 文件放在散列中外,我还需要了解打印和浏览特定元素的语法。非常感谢您提前。
解决方案
这是一个如何将数据放入哈希中的示例,%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];
推荐阅读
- react-native - 带有 React Native 的 Expo PDF 查看器
- vue.js - Vuetify list-item-group,列表项的价值属性中的数组?
- xcode - 在 Xcode 中启动项目后,如何正确添加源代码管理?
- json - 使用循环从Linux中的文本文件创建//附加JSON数组
- javascript - AJAX 表示 WEBMETHOD 成功,但它从未真正触发后面代码的 webmethod
- kubernetes - 连接FFServer多个实例
- ruby-on-rails - 在我的 Rails 应用程序中为用户创建汽车的问题
- javascript - 如何在不重新加载 Webpack-Dev-Server 的情况下重新加载 Service-Worker(工作箱)?
- android - Android Mockito - 模拟枚举?
- android - 如何连接片段和布局