【问题标题】:printing values to file and to terminal将值打印到文件和终端
【发布时间】:2014-12-23 02:18:06
【问题描述】:

这里是超级小白。 试图让$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

所以我只得到最后一行。

【问题讨论】:

标签: perl parsing printing


【解决方案1】:

出现您的问题是因为您多次重新打开同一个文件并在每次打开时覆盖其内容。如果您从逻辑上考虑,您希望为每个解析的输入文件创建一个输出文件,因此最好在打开输入文件时创建输出文件:

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";
    }
}

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 2019-05-04
    • 2010-10-06
    • 2017-09-26
    • 2020-03-09
    • 2013-06-27
    • 2013-09-14
    • 2010-09-22
    相关资源
    最近更新 更多