0

实际上这个问题是这个的副本http://stackoverflow.com/questions/12813317/text-file-operation-in-perl 。但是在这里,我正在尝试按照老板的建议打印一些差异 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";  
    }
}

实际输出:

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
4

2 回答 2

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";
    }
}
于 2012-10-10T10:06:06.067 回答
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 ;
于 2012-10-10T10:08:20.337 回答