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 に答える