输入:
NAME Age Occupation Place
X1 43 Artist Italy
X2 42 Artist Germany
Y1 56 Artist France
我需要提取NAME和年龄列。
我的代码:
#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils;
my $file = @ARGV[0];
open(FH, "< $file") or die "Cannot open $file for reading: $!";
my @array = <FH>;
close FH or die "Could not open file: $!";
open(OUT, ">$file") or die "Cannot open $file for write access: $!";
print OUT splice(@array,4);
close OUT or die "Could not close file: $!";
open(MYFILE,"< $file") or die "Cannot open $file for read access: $!";
open(my $OFILE, '>Output.txt') or die "Cannot create file for output: $!";
my @wanted = ("NAME","AGE");
my @output = qw/NAME AGE/;
my @fields = split /\t/, <MYFILE>;
chomp @fields;
print $OFILE join("\t",@output), "\n";
while(<MYFILE>)
{
chomp;
my %row;
@row{@fields} = split /\t/;
my @wanted_data = map{$row{$_}} @wanted;
print $OFILE join("\t", @wanted_data), "\n";
}
close $OFILE or die "Error closing $OFILE: $!";
我收到错误,例如在连接或字符串中使用未初始化的值
print $ OFILE join(“\ t”,@wanted_data),“\ n”;
所以标题单独在我的output.txt
谢谢, N.
答案 0 :(得分:1)
如果您只想要前两列,则可以简化这些行的split
并输出前两个字段:
#!/usr/bin/perl
use strict;
use warnings;
use feature qw(say);
use Data::Dumper;
while (<DATA>) {
chomp;
my ($name, $age) = split /\s+/;
say "$name $age";
}
__DATA__
X1 43 Artist Italy
X2 42 Artist Germany
Y1 56 Artist France
这是一个单行版本:
perl -anE 'say "@F[0,1]"' input.txt
答案 1 :(得分:1)
你在这里做了很多不必要的工作..
假设您知道姓名和年龄是前两列:
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $csv = Text::CSV->new;
my $file = $ARGV[0];
open my $fh, "<", $file or die "Cannot open $file for reading: $!";
open my $OFILE, '>', 'Output.txt' or die "Cannot create file for output: $!";
while ( my $row = $csv->getline( $fh ) ) {
print $OFILE $row->[0], "\t", $row[1], "\n";
}
close $fh;
close $OFILE;