使用perl脚本将数据从制表符分隔的文件提取到新的文本文件

使用perl脚本将数据从制表符分隔的文件提取到新的文本文件,perl,Perl,输入: 我需要提取姓名和年龄列 我的代码: NAME Age Occupation Place X1 43 Artist Italy X2 42 Artist Germany Y1 56 Artist France #/usr/bin/perl 严格使用; 使用警告; 使用列表::MoreUtils; 我的$file=@ARGV[0]; 打开(FH,“$file”)或死亡“无法打开$file进行写访问:$!”; 打印输出接头(@array,4);

输入:

我需要提取姓名和年龄列

我的代码:

NAME Age Occupation Place
X1   43   Artist     Italy
X2   42   Artist     Germany
Y1   56   Artist     France
#/usr/bin/perl
严格使用;
使用警告;
使用列表::MoreUtils;
我的$file=@ARGV[0];
打开(FH,“<$file”)或die“无法打开$file进行读取:$!”;
my@array=;
关闭FH或死亡“无法打开文件:$!”;
打开(OUT,“>$file”)或死亡“无法打开$file进行写访问:$!”;
打印输出接头(@array,4);
关闭或死亡“无法关闭文件:$!”;
打开(MYFILE“<$file”)或死亡“无法打开$file进行读取访问:$!”;
打开(my$OFILE,'>Output.txt')或死亡“无法为输出创建文件:$!”;
我的@通缉=(“姓名”、“年龄”);
我的@output=qw/姓名年龄/;
我的@fields=split/\t/;
咀嚼田野;
打印$OFILE join(“\t”,@output),“\n”;
while()
{
咀嚼;
我的%行;
@行{@fields}=split/\t/;
my@wanted_data=map{$row{$}}@wanted;
打印$OFILE join(“\t”,@wanted\u data),“\n”;
}
关闭$OFILE或die“错误关闭$OFILE:$!”;
我得到的错误类似于在连接或字符串中使用未初始化的值 打印$OFILE join(“\t”,@wanted\u data),“\n”
因此,在我的output.txt文件中,只有标题被打印出来

谢谢,
N.

如果只需要前两列,您可以简单地
拆分这些行并输出前两个字段:

#!/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: $!";

你在这里做了那么多不必要的工作

假设您知道姓名和年龄是前两列:

perl -anE 'say "@F[0,1]"' input.txt
#/usr/bin/perl
严格使用;
使用警告;
使用Text::CSV;
my$csv=文本::csv->新建;
my$file=$ARGV[0];

打开我的$fh,“欢迎使用堆栈溢出。我建议始终如一地使用词法文件句柄,而不是混合使用词法和非词法文件句柄。您在关闭的错误消息中引用了“打开”。似乎有过多的文件打开和关闭。打开文件,读取文件,关闭文件,打开文件,写入文件,关闭文件,打开文件,打开输出文件,读取和写入文件,然后关闭一个但不是两个打开的文件。我对
@row{@fields}=split/\t/。您不能使用AFAICS。@Jonathen Leffler,Ok和Thx
perl -anE 'say "@F[0,1]"' input.txt
#!/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;