2016-01-20 74 views
0

我的程序讀取一個文件,我不想把空行檢測空行(僅包含空格)在Perl

​​

但是這個代碼同時打印空行

的文件我測試包含:

Ms. Ruth Dreifuss Dreifuss Federal Councillor Federal ruth 
      
sir christopher warren US Secretary of state secretary of state 
      
external economic case federal economic affair conference the Federal Office case 
      
US bill clinton bill clinton Mr. Bush 
      
Nestle food cs holding swiss Swiss Performance Index Performance 
+2

你可以發佈「空行」的轉儲嗎? 'print join'',映射ord,split //,$ ligne'。 – choroba

+0

程序打印10 –

回答

3

我認爲這是因爲使用\n代碼內。只需從代碼中刪除\n,它應該沒問題。

通常人在從文件中讀取一行以消除行尾字符之後做chomp

1

原因也是您要添加一個新行,你的字符串的結尾已經有它「$ LIGNE \ n」換行,所以使用格格如下

我想這樣做的更好的方法是用下一個(跳到下一個循環迭代),因爲它消除了從你的代碼中括號:

while (<FICC>) { 
    my $ligne=chomp $_; 
    next if $ligne =~ /^\s*$/; 
    print " $ligne\n"; 
} 
3

編寫一個簡單的方法可能是反轉的邏輯,只會打印線包含非空白字符。

更新:使用您的樣本數據演示:

#!/usr/bin/perl 

use strict; 
use warnings; 

while (<DATA>) { 
    my $ligne = $_; 

    if ($ligne =~ /\S/) { 
    print " $ligne"; 
    } 
} 

__END__ 
Ms. Ruth Dreifuss Dreifuss Federal Councillor Federal ruth 

sir christopher warren US Secretary of state secretary of state 

external economic case federal economic affair conference the Federal Office case 

US bill clinton bill clinton Mr. Bush 

Nestle food cs holding swiss Swiss Performance Index Performance 

輸出:

Ms. Ruth Dreifuss Dreifuss Federal Councillor Federal ruth 
sir christopher warren US Secretary of state secretary of state 
external economic case federal economic affair conference the Federal Office case 
US bill clinton bill clinton Mr. Bush 
Nestle food cs holding swiss Swiss Performance Index Performance 

這似乎是正確的我。

+2

我認爲OP的問題在於他們打印的是「'ligne \ n」'而沒有篡改原始換行符,所以輸出是雙倍行距 – Borodin

+0

好點。我會編輯。 –

+0

問題是如果我添加'其他{打印'ligne「}'這個打印空行,所以它檢測到空行,但其他沒有做任何事情 –