Bulknews::Subtech RSSフィード

2006/06/14 (水)

Encode::JavaScript::UCS 11:45  Encode::JavaScript::UCS - Bulknews::Subtech を含むブックマーク はてなブックマーク -  Encode::JavaScript::UCS - Bulknews::Subtech

http://search.cpan.org/~itwarrior/Unicode-Escape-0.0.1/

さすがにこの名前はやりすぎでしょう。。。 あと実装も再発明感が。

Encode.pm を使う=5.8 前提なら Unicode::String のほとんどの機能は不要。Encode::Encoding として実装するのが普通だろうなあ。ということで、

package Encode::JavaScript::UCS;
use strict;
use warnings;
use base qw(Encode::Encoding);
use Encode 2.12 (); # for callbacks

__PACKAGE__->Define('JavaScript-UCS');

sub decode($$;$){
    my ($obj, $buf, $chk) = @_;
    $buf =~ s/\\u([0-9a-f]{4})/chr(hex($1))/eig;
    $_[1] = '' if $chk; # this is what in-place edit means
    return $buf;
}

sub encode($$;$){
    my ($obj, $str, $chk) = @_;
    $str = Encode::encode("ascii", $str, sub { sprintf("\\u%04x", $_[0]) });
    $_[1] = '' if $chk; # this is what in-place edit means
    return $str;
}

1;

__END__

package main;
use Data::Dumper;
use Encode;
my $name = "\x{5BAE}\x{5DDD}\x{9054}\x{5F66}";
my $escaped = encode("JavaScript-UCS", $name);
warn Dumper $escaped;

$name = decode("JavaScript-UCS", $escaped); 
warn Dumper $name;