我是Perl的新手,我遇到了精神上的障碍.我需要从制表符分隔文件中提取信息,如下所示.
#name years risk total
adam 5 100 200
adam 5 50 100
adam 10 20 300
bill 20 5 100
bill 30 10 800
Run Code Online (Sandbox Code Playgroud)
在此示例中,制表符分隔文件显示投资的长度,风险金额以及投资结束时的总金额.
我想解析这个文件,并为每个名称(例如adam)计算投入的年数5 + 5,并计算收入总和(200-100)+(100-50)+(300-20).我还想保存每个名字的总数(200,100,300).
这是我到目前为止所尝试的:
my $filename;
my $seq_fh;
open $seq_fh, $frhitoutput
or die "failed to read input file: $!";
while (my $line = <$seq_fh>) {
chomp $line;
## skip comments and blank lines and optional repeat of title line
next if $line =~ /^\#/ || $line =~ /^\s*$/ || $line =~ /^\+/;
#split each line into array
my @line = split(/\s+/, $line);
my $yeartotal = 0;
my $earning = 0;
#$line[0] = name
#$line[1] = years
#$line[2] = start
#$line[3] = end
while (@line[0]){
$yeartotal += $line[1];
$earning += ($line[3]-$line[2]);
}
}
Run Code Online (Sandbox Code Playgroud)
我错在哪里的想法?
你错了: while(@line[0]){
我会做:
my $seq_fh;
my %result;
open($seq_fh, $frhitoutput) || die "failed to read input file: $!";
while (my $line = <$seq_fh>) {
chomp $line;
## skip comments and blank lines and optional repeat of title line
next if $line =~ /^\#/ || $line =~ /^\s*$/ || $line =~ /^\+/;
#split each line into array
my @line = split(/\s+/, $line);
$result{$line[0]}{yeartotal} += $line[1];
$result{$line[0]}{earning} += $line[3] - $line[2];
}
Run Code Online (Sandbox Code Playgroud)