【发布时间】:2017-08-07 08:55:58
【问题描述】:
我的 perl 脚本中有以下命令:
my @files = `find $basedir/ -type f -iname '$sampleid*.summary.csv'`; #there are multiple summary.csv files in my basedir. I store them in an array
my $summary = `tail -n 1 $files[0]`; #Each summary.csv contains a header line and a line with data. I fetch here the last line.
chomp($summary);
my @sp = split(/,/,$summary); # I split based on ','
my $gender = $sp[11]; # the values from column 11 are stored in $gender
my $qc = $sp[2]; # the values from column 2 are stored in $gender
现在,我遇到了我的 *summary.csv 文件的列数不同的情况。它们都有 2 行,其中第一行代表标题。
我现在想要的不是将第 11 列中的值存储在性别中,而是我想将“性别”列中的值存储在 $gender 中。
我怎样才能做到这一点?
首先尝试解决方案:
my %hash = ();
my $header = `head -n 1 $files[0]`; #reading the header
chomp ($header);
my @colnames = split (/,/,$header);
my $keyfield = $colnames[#here should be the column with the name 'Gender']
push @{ $hash{$keyfield} };
my $gender = $sp[$keyfield]
【问题讨论】:
-
你必须获取标题行和你想要的行。然后拆分两者,并以标头作为键构建哈希,然后读取所需键的值。您的代码看起来更像是用 Perl 编写的 shell 脚本,而不是 Perl 程序。为什么不直接使用 Perl 打开和读取文件,或者直接使用 Text::CSV?
-
@simbabque:我正在改编一个我自己没有从头开始编写的现有脚本。我已经在问题中添加了第一次尝试解决方案。但是,我坚持“以标头为键构建哈希”。
-
你没有使用哈希。
-
查看我的更新答案。
-
@simbabque:是的,我做到了。我接受了你的回答。
标签: perl