2012-10-10 104 views
0

其實這個問題是http://stackoverflow.com/questions/12813317/text-file-operation-in-perl這個副本。但在這裏我想打印一些差異鄰/對我的老闆:(txt文件以表格形式輸出

我能獲得任何幫助的建議:)

我有一個文本文件,在其中一擊是數據:

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 

回答

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"; 
    } 
} 
+2

你應該使用詞法文件句柄。 – simbabque

+0

嗯,當我看到typeglobs(是的,我就是那個年齡)時,我感覺所有內心都很溫暖。但你是對的。 – January

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 ; 
+1

我更喜歡'close $ IN'來關閉($ IN)'。 – January