0

我写了一个脚本,我在 UTF-8 编码的 HTML 文件中啜饮,然后将其解析为带有HTML::Tree. 问题是解析字符串后不再标记为 UTF-8。

由于_utf8_on()不推荐设置标志的方法,我正在寻找正确的方法。

我的简化代码示例:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use utf8::all;
use autodie;
use HTML::Tree;
use Encode qw/is_utf8/;

my $file = shift;
my $tree;

if ($file) {
    my $content = slurp_in( 'file' => $file );
    $tree = html_tree('content' => $content);
} else {
    die "no file";
}

my $title = $tree->look_down(_tag => 'title');
$title = $title->as_HTML('');

if ( is_utf8( $title ) ) {
    say "OK: $title";
} else {
    say "NOT OK: $title";
}

## SUBS
##
sub slurp_in {
    my %v = @_;

    open(my $fh, "<:utf8", $v{file}) || die "no $v{file}: $!";
    local $/;
    my $content = (<$fh>);
    close $fh;

    if ($content) {
        return $content;
    } else {
        die "no content in $v{file} !";
    }
}

sub html_tree {
    my %v = @_;
    my $tree = HTML::Tree->new();
    $tree->utf8_mode(1); ## wrong call here, no such method, but no warnings on it!
    $tree->parse( $v{content} );

    if ($tree) {
        return $tree;
    } else {
        die "no tree here";
    }
}
4

1 回答 1

6

您的代码过于复杂,您使用 utf8::all 并手动解码并一次调用该奇怪的方法。反问一句,您期望以这种方式实现什么?我没有耐心去详细了解哪里出了什么问题,特别是因为你没有发布任何你的程序未能达到预期的输入,所以我将它大大简化为一个更简单的。这有效:

#!/usr/bin/env perl
use 5.010;
use strict;
use warnings FATAL => ':all';
use File::Slurp qw(read_file);  # autodies on error
use HTML::Tree qw();

my $file = shift;
die 'no file' unless $file;

my $tree = HTML::Tree->new_from_content(
    read_file($file, binmode => ':encoding(UTF-8)')
);

my $title = $tree->look_down(_tag => 'title');
$title->as_HTML(''); # returns a Perl string
于 2011-08-29T15:57:19.787 回答