2015-04-15 58 views
2

因此,我目前正在嘗試編寫一個perl腳本,該腳本讀取到一個文件並寫入另一個腳本。目前,我一直有這個問題是在這樣的Perl:唧唧喳喳的字符串後,它不會打印字符串的值

BetteDavisFilms.txt 
1. 
Wicked Stepmother (1989) as Miranda 
A couple comes home from vacation to find that their grandfather has … 
2. 
Directed By William Wyler (1988) as Herself 
During the Golden Age of Hollywood, William Wyler was one of the … 
3. 
Whales of August, The (1987) as Libby Strong 
Drama revolving around five unusual elderly characters, two of whom … 

文件去除解析rows.I飼料換行字符最終我試圖把它變成一個格式像這樣

1,Wicked Stepmother ,1989, as Miranda,A couple comes home from vacation to … 
2,Directed By William Wyler ,1988, as Herself,During the Golden Age of … 
3,"Whales of August, The ",1987, as Libby Strong,Drama revolving around five… 

它成功刪除識別到每個數字,但然後我想刪除\ n然後替換「。」。與「,」。可悲的是,chomp函數破壞或隱藏數據某些時候,當我在chomping $ row後打印時,沒有顯示......我應該怎麼做才能糾正這個問題?

#!bin/usr/perl 
use strict; 
use warnings; 

my $file = "BetteDavisFilms"; 
my @stack =(); 

open (my $in , '<', "$file.txt") or die "Could not open to read \n "; 
open (my $out , '>', "out.txt") or die "Could not out to file \n"; 

my @array = <$in>; 

sub readandparse() { 
    for(my $i = 0 ; $i < scalar(@array); $i++) { 
     my $row = $array[$i]; 

     if($row =~ m/\d[.]/) { 
      parseFirstRow($row); 
     } 
    } 
} 

sub parseFirstRow() { 
    my $rowOne = shift; 
    print $rowOne; ####prints a number 
    chomp($rowOne); 
    print $rowOne; ###prints nothing 
    #$rowOne =~ s/./,/; 
} 

#call to run program 
readandparse(); 
+0

'打開我的,$ <:CRLF「, 」file.txt的「;' – BryanK

回答

3

您的文字以CR LF結尾。你刪除LF,留下CR。您的終端正在將光標歸位到CR上,導致下一行輸出覆蓋最後一行輸出。

$ perl -e' 
    print "XXXXXX\r"; 
    print "xxx\n"; 
' 
xxxXXX 

修復輸入文件

dos2unix file 

或刪除CR與LF一起。

s/\s+\z// # Instead of chomp 
+1

你的意思是'S/\ r \ Z^//',我相信。 – tchrist

+1

@tchrist,如果你必須處理一個格式,其尾部空格是重要的,我可憐你,你會使用's \\ R \ z //'。對於我們其他人來說,'s/\ s + \ z //'更好。 – ikegami

+0

chomp while chomp; – Joshua