Hatena::ブログ(Diary)

punitan (a.k.a. punytan) のメモ このページをアンテナに追加 RSSフィード

Fork me on GitHub

2010-11-14

[]HTML::Entities::Recursive というモジュールを書いた

no title

HTML::Entities::Recursive

Encode / decode strings of complex data structure with HTML entities recursively

SYNOPSIS

    use HTML::Entities::Recursive;
    my $recursive = HTML::Entities::Recursive->new;

    my $foo = {
        text => '<div></div>',
    };

    my $bar = $recursive->encode_numeric($foo);
    print $bar->{text}; # prints '&lt;div&gt;&lt;/div&gt;'

DESCRIPTION

HTML::Entities::Recursive provides API to encode / decode strings of complex data structure with HTML entities recursively.

To avoid conflicting with HTML::Entities' functions, HTML::Entities::Recursive is written in OO-style.

There is no function to be exported.

To proxy content provider's API, we sometimes want to bulk decode and encode complex data structure that contains escaped strings with untrustworthy way. (yes, response from Twitter API :)

HTML::Entities::Recursive helps you to make output safe with ease.

METHODS

  • new

new() takes no argument.

  • encode( $structure )
  • encode( $structure, $unsafe_chars )
  • encode_numeric( $structure )
  • encode_numeric( $structure, $unsafe_chars )
  • decode( $structure )

HTML::Entities - search.cpan.org refers to $unsafe_chars.

Methods correspond to HTML::Entities' functions but the first argument can be hashref, arrayref or scalarref.

Internally, all corresponding functions are called in array context. So you cannot use those methods in void context.

That is,

  • Use methods in scalar or array context.
  • Methods do not modify original structure.

使いどころ

perldoc にもあるように、 Twitter からのレスポンスをまとめて (en|de)code かけるときに役に立ちます

再帰

再帰に関しては Sub::Recursive - search.cpan.org というモジュールがあるのでそれを使ってます

注意点

HTML::Entities は渡した引数を直接書き換えたりできるのですが、このモジュールではそういった使い方はできません。元のデータは変更されないので戻り値を使う。