2011-07-21 120 views
0
   use strict; 
      use warnings; 
      open(FILE4,"cool.txt"); 
      open(FILE6,">./mool.txt"); 
      $line = <FILE4>; 
       while ($line ne "") 
      { 
       @array = split(/,/,$line); 
       $line = <FILE4> ; 
       print FILE6 ($array[0]); 
       print FILE6 ("\t"); 
       print FILE6 ($array[1]); 
       print FILE6 ("\t"); 
       print FILE6 ($array[2]); 
      } 

這些是我用perl編寫的代碼。但代碼工作不正常。它爲每一個下一行提供標籤空間。但是我不需要爲每一個新行選擇TAB空間。讓我告訴你如何輸出。誰能告訴我錯誤在哪裏?

  name   contact  email 
         samy   32344245   [email protected] 
         alex   231414124   [email protected] 

這是我看到我的mool.txt銼的第一行其從我面對的標籤space.I我試圖找出錯誤is.Can請人的nextline工作fine.But讓我知道代碼的問題呢?我已經經歷過很多次,但去摸不清它out.Thank你

正如有人問的IM顯示你輸入文件

 "name","contact","email" 
     "samy","32344245","[email protected]" 
+0

請告訴我們前兩輸入文件的行號 –

+3

如果數據變得更復雜,則可能會遇到問題。例如,你將如何處理姓名或聯繫人字段中的逗號?您可能需要查看CSV模塊,例如[Text :: CSV或類似的](http://search.cpan.org/search?query=text%3A%3Acsv&mode=all)。 – Mike

+0

該文件在*數據之前有一個製表符* :) –

回答

2

將這個語句while循環中。 chomp 這應該是從文件讀取一行後的第一行。這將刪除不需要的空間。

use strict; 
use warnings; 
open(FILE4,"cool.txt"); 
open(FILE6,">./mool.txt"); 

while (<FILE4>) 
{ 
    chomp; #This will remove unwanted spaces 
    @array = split(/,/,$_); #$_ will represent the line which is read 
    print FILE6 ($array[0]); 
    print FILE6 ("\t"); 
    print FILE6 ($array[1]); 
    print FILE6 ("\t"); 
    print FILE6 ($array[2]); 
    print FILE6 ("\n"); 
} 
+1

'chomp'不會從字符串中刪除任何尾隨標籤,除非更新'$ /'。 –

+0

@eugene查看此代碼片段&輸出 '#!/ usr/bin/perl $ x = ; print「Without chomp:| $ x |」; chomp($ x); 打印 「\ n在格格:| $ X |」;' 輸出 '[tethomas @〜/ perl的訓練] ./ t.pl 你好 沒有格格:|您好 | chomp之後:|你好|' – cppcoder

+0

@cpp eugene是正確的,來自[perldoc perlfunc](http://perldoc.perl.org/functions/chomp.html)'這個更安全的chop版本刪除任何與之對應的尾部字符串$ /(也稱爲$ INPUT_RECORD_SEPARATOR ...)的當前值 – TLP

4

你可能有輸入文件中行的開始/結尾有空格。
嘗試用s///來剝離:

use strict; 
use warnings; 

open my $in, "<", "cool.txt" or die $!; 
open my $out, ">", "mool.txt" or die $!; 

while (my $line = <$in>) { 
    $line =~ s/^\s+|\s+$//g;      
    my @array = split(/,/, $line); 
    print $out join("\t", @array), "\n"; 
}  
+0

請使用三參數打開。順便說一下,爲什麼語法突出顯示在這裏再次失敗? – Svante

+0

我第二個「open」的三參數形式。此外,應該總是檢查打開文件的返回值。 –

2

你似乎在做的是將此文件從逗號分隔改爲製表符分隔。如果是這樣,這可能是一個更簡單的方法來做到這一點:

while (<>) { 
    s/,/\t/g; 
    print; 
} 

,然後用它是這樣的:

$ script.pl cool.txt > mool.txt 

你甚至可能逃脫一行代碼:

perl -pwe 's/,/\t/g' cool.txt > mool.txt 

或者,如果你有奇怪的空白:

perl -pwe 's/^\s+|\s+$//g; s/,/\t/g' cool.txt > mool.txt 

或者,更安全的版本,使用Text::CSV。這將爲您處理複雜的數據等。如果你得到空白輸出,可能是你的額外空白搞砸了。如果是這樣,你可以運行一個班輪上面沒有s/,/\t/g線得到輸入文件的「清理後的」版本:

perl -pwe 's/^\s+|\s+$//g;' cool.txt > cool_clean.txt 

腳本:

use warnings; 
use strict; 
use Text::CSV; 
use autodie; 

my $csv_in = Text::CSV->new(); 
my $csv_out = Text::CSV->new({ sep_char => "\t", eol => "\n" }); 
open my $fh, '<', 'data.csv'; 
open my $out, '>', 'mool.txt'; 
while (my $row = $csv_in->getline($fh)) { 
    $csv_out->print($out, $row); 
} 
相關問題