2012-10-10 3 views
0

사실이 질문은 http://stackoverflow.com/questions/12813317/text-file-operation-in-perl 사본입니다. 내 보스 :(Txt 파일 표 형식으로 출력

내가 어떤 도움을 기대할 수에 의해 제안하지만, 여기에 나는 약간은 diff 오/피를 인쇄하려고 :)

내가 타격 데이터 인 텍스트 파일이 있습니다?

#!/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 
여기

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; 
.... 
.... 
내 코드입니다

예상 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

글쎄, 타입 글럽 (예, 저는 그 시대입니다)을 볼 때 내면이 따뜻하고 멋있다고 느낍니다. 그러나 당신 말이 맞습니다. – 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)'에'close $ IN'을 선호합니다. – January