2014-10-27 85 views
1

這裏的超級nooby。 試圖讓$cssurl打印到文件與終端,但只獲得一個值打印在文件與終端打印所有東西。我如何修改下面的代碼來獲得我需要的?將文件打印到文件並傳送到終端

下面的代碼:

use lib '/Users/lialin/perl5/lib/perl5'; 
use strict; 
use warnings; 
use feature 'say'; 
use File::Slurp 'slurp'; # makes it easy to read files. 
use Mojo; 
use Mojo::UserAgent; 
use URI; 

my $calls_dir = "Ask/"; 
opendir(my $search_dir, $calls_dir) or die "$!\n"; 
my @html_files = grep /\.html$/i, readdir $search_dir; 
closedir $search_dir; 
#print "Got ", scalar @files, " files\n"; 

foreach my $html_files (@html_files) { 
    my %seen   =(); 
    my $current_file = $calls_dir . $html_files; 
    open my $FILE, '<', $current_file or die "$html_files: $!\n"; 

    my $dom = Mojo::DOM->new(scalar slurp $calls_dir . $html_files); 
    print $calls_dir . $html_files; 

    for my $csshref ($dom->find('a[href]')->attr('href')->each) { 
     my $cssurl = URI->new($csshref)->abs($calls_dir . $html_files); 

     open my $fh, '>', "Ask/${html_files}.result.txt" or die $!; 
     $fh->print("$html_files\n"); 
     $fh->print("$cssurl\n"); 
     #$fh->print("\t"."$_\n"); 
     print "$cssurl\n"; 
     #print $file."\t"."$_\n"; 
    } 
} 

在終端中我得到這個:

http://www.scigene.com/ 
about 500 of other urls in here that stack overflow won't let me post 
http://feedback.ask.com 

寫入到文件中我得到這個:

Agilent_Technologies_ask.html 
http://feedback.ask.com 

所以我只是得到最後線。

+0

你需要什麼是有用的一個例子。 – Sobrique 2014-10-27 19:35:32

+0

如果我在終端上運行上面的腳本,我可以得到:http://www.scigene.com/ http://www.scigene.com/contact.php http://www.scigene.com/cms。 php?mlink =訂購&mlinkid = 31&cmsid = 84 http://www.scigene.com/cms.php?mlink=Corporate&mlinkid=29&cmsid=73 http://www.scigene.com/cms.php?mlinkid=43&mlink= Support&cmsid = 81 http://www.scigene.com/cms.php?mlinkid=29&mlink=Corporate&cmsid=72 -in the file I just get this-Agilent_Technologies_ask.html http://feedback.ask.com – tlialin 2014-10-27 19:40:45

+4

You在循環中以寫入模式('>')打開文件,這會在每次迭代中截斷文件。您應該在循環之前打開文件。有關詳細信息,請參見['perldoc -f open'](http://perldoc.perl.org/functions/open.html)。 – ThisSuitIsBlackNot 2014-10-27 19:43:48

回答

0

您的問題出現是因爲您多次重新打開同一文件並在每次打開內容時覆蓋內容。如果您在邏輯想想,你想創建您解析每個輸入文件一個輸出文件,所以這將是最好創建輸出文件,當你打開輸入文件:

my $dom = Mojo::DOM->new(scalar slurp $calls_dir . $html_files); 
open my $fh, '>', "Ask/${html_files}.result.txt" or die $!; 

如果有任何材料只需要打印一次(文件頭等),這需要在開始循環訪問URL之前完成。

for循環看起來現在這個樣子:

foreach my $html_files (@html_files) { 

    my $dom = Mojo::DOM->new(scalar slurp $calls_dir . $html_files); 
    print $calls_dir . $html_files; 

    open my $fh, '>', "Ask/${html_files}.result.txt" or die $!; 
    $fh->print("$html_files\n"); 

    for my $csshref ($dom->find('a[href]')->attr('href')->each) { 
     my $cssurl = URI->new($csshref)->abs($calls_dir . $html_files); 

     $fh->print("$cssurl\n"); 
     print "$cssurl\n"; 
    } 
}