2011-07-11 51 views
-1

一行我已經Perl的以下,結果文件僅打印使用Perl

open (FILE, 'file.htm'); 
my $tree = HTML::TreeBuilder->new_from_content(do { local $/; <FILE> }); 

for ($tree->look_down('class' => 'postbody')) 
{  
    my $location = $_->look_down('class' => 'posthilit')->as_trimmed_text;  
    my $comment = $_->look_down('class' => 'content')->as_trimmed_text;  
    my $name  = $_->look_down('_tag' => 'h3')->as_text;  

    $name =~ s/^Re:\s*//;  $name =~ s/\s*$location\s*$//;  
    print "Name: $name\nLives in: $location\nCommented: $comment\n"; 

    my $csv = Text::CSV->new(); 
    $csv->column_names('field1', 'field2', 'field3'); 
    $csv->print ($fh, [$name,$location,$comment]); 
    open $fh, ">", "file.csv" or die "ERROR: $!"; 
    close $fh or die "$!"; 
} 

這僅輸出一個從輸入文件到新的「FILE.CSV」文件中的行。 我怎樣才能得到它把所有的結果放到結果文件中。

在此先感謝。

+2

'$ name','$ location'和'$ comment'從哪裏來? – Toto

+0

我已經在腳本的其餘部分添加了 – Ebikeneser

回答

1

因爲您只撥打$csv->print一次,所寫的代碼只打印一行。由於您顯然擁有多行數據,因此您需要創建一個可打印所有行的循環。事情是這樣的:

while (my ($name, $location, $comment) = next_record()) { 
    $csv->print($fh, [$name, $location, $comment]); 
} 

我不能給你任何比這更詳細的回答沒有看到你的代碼的其餘部分,並知道變量$name, $location, $comment是如何分配的。


更新的問題進行修改後:

您有for ($tree->look_down(...))一個循環,這是罰款,並採取我上面描述的while環路的地方。但是,按照當前編寫的內容,您每次都通過循環創建一個新的$csv對象和一個新文件!這就是爲什麼你只有每一行都在輸出文件中有一行。你需要採取以下行,並把它們for循環的開始:

my $csv = Text::CSV->new(); 
$csv->column_names('field1', 'field2', 'field3'); 
open $fh, ">", "file.csv" or die "ERROR: $!"; 

循環,你只需要做到這一點:

$csv->print ($fh, [$name,$location,$comment]); 

然後,一旦循環已完成,您可以這樣做:

close $fh or die "$!"; 
+0

多數民衆贊成好,它似乎不喜歡next_record部分呢?帶來一個未定義的子程序錯誤... – Ebikeneser

+0

@Jambo,那是因爲'next_record'就是我編造的一些東西,以說明如何編寫循環。 *您*是瞭解您的數據來自何處的人,*您是知道如何迭代所有記錄以將其寫入文件的人。 –

+0

我明白了,我已經在第一個腳本中加入了你所說的循環,但是仍然不確定在new_record部分放置什麼? – Ebikeneser

-1

只是檢查的Text::CSV 的文檔,你應該打開文件進行讀取,並有一個函數getline方法。

+0

不相關。他想知道如何寫*數據,而不是讀*它。 –

+0

是的,我的錯誤,好像我誤解了這個問題。 –

0

使用eol =>「\ n」比如...

my $csv = Text::CSV->new ({ binary => 1, eol => "\n" }) 
    or die "Cannot use CSV: ".Text::CSV->error_diag();