0

我想将一些文件的内容保存到一个新文件中,我执行以下操作:

use strict;
use warnings;
use HTML::TreeBuilder::XPath;

my ($dir) = @ARGV;
my @files = glob "details/*";
my $filename = 'target.txt';

for my $file (@files) {
  my $tree = HTML::TreeBuilder::XPath->new_from_file($file);
  my @opacity = $tree->findnodes_as_strings('//div[@class="opacity description"]');
  open my $fh, '>>', $filename;
  print $fh for @opacity; 
}

不幸的是,它不起作用。我不明白为什么?

4

1 回答 1

2
  1. 检查返回值open

    open my $fh ">>", $filename or die "Can't open $filename: $!";
    

    当“某事不工作”时,这可以提供宝贵的见解。

  2. 您的 for 语法print不明确。使用printsay喜欢

    print FILEHANDLE LIST
    print {EXPR} LIST     # EXPR has to produce a filehandle object
    print LIST            # prints to the `select`ed filehandle, usually STDOUT
    print                 # prints $_ by default
    

    因此,您要明确指定要打印的内容,并且可能还要在@opacity. 所以要么

    print {$fh} "$_\n" for @opacity;
    

    use feature 'say'(perl 5.10 及更高版本):

    say {$fh} $_ for @opacity;
    
于 2013-02-02T11:25:06.880 回答