实际上这个问题是http://stackoverflow.com/questions/12813317/text-file-operation-in-perl
这个问题的副本。但在这里,我正在尝试按照我的老板的建议打印一些diff o / p :(
我可以期待任何帮助吗? :)
我有一个文本文件,其中打击是数据:
Id:001;status:open;Name:AB;Id:002;status:open;Name:AB;Id:003;status:closed;Name:BC;
Id:004;status:open;Name:AB;Id:005;status:closed;Name:BB;Id:006;status:open;Name:CD;
....
....
这是我的代码:
#!/usr/bin/perl -w
use strict;
open IN, "<", "ABC.txt"
or die"Can not open the file $!";
my @split_line;
while(my $line = <IN>) {
@split_line = split /;/, $line;
for (my $i = 0; $i <= $#split_line; $i += 2) {
print "$split_line[$i]"." "."$split_line[$i+1]\n";
}
}
实际o / p:
Id:001 status:open Name:AB
Id:002 status:open Name:AB
预期的O / p
Id Status Name
001 open AC
002 open AB
003 close BC
答案 0 :(得分:1)
#!/usr/bin/perl -w
use strict;
open IN, "<", "ABC.txt"
or die"Can not open the file $!";
my @split_line;
print "Id\tStatus\tName\n";
while(my $line = <IN>) {
@split_line = split /[;:]/, $line;
for (my $i = 1; $i <= $#split_line; $i += 6) {
print "$split_line[$i]"."\t"."$split_line[$i+2]"."\t"."$split_line[$i+4] \n";
}
}
答案 1 :(得分:0)
您的脚本不会生成您描述的输出,这是它在我的系统上生成的内容:
Id:001 status:open
Name:AB Id:002
status:open Name:AB
Id:003 status:closed
Name:BC
Id:004 status:open
Name:AB Id:005
status:closed Name:BB
Id:006 status:open
Name:CD
我认为你应该修改如下:
#!/usr/bin/perl
use strict;
use warnings;
open (my $IN, "<", "ABC.txt") or die "Can not open the file $!";
my @split_line;
while(<$IN>) {
@split_line = split /;/ ;
foreach ( @split_line ) { s/.*?:// ; }
for (my $i = 0; $i < $#split_line; $i += 3) {
print join( " ", @split_line[$i .. $i+2] ) . "\n" ;
}
}
close $IN ;