Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

UNIVERSAL::to_json リリース

UNIVERSAL::to_json なんてのをこさえたのですが、DIS られる悪寒をひしひしと感じながら、CPAN にうpってみたりしました。UNIVERSAL::to_yaml インスパイヤ。つか、autobox かっけ!

use UNIVERSAL::to_json;

my $obj = Foo->new;
print $obj->to_json;

    use autobox; # activate autobox

    print 'scalar value'->to_json;   #=> "scalar value"
    print [qw(list items)]->to_json; #=> ["list","items"]
    print {key => 'value'}->to_json; #=> {"key":"value"}

    no autobox;  # inactivate autobox

    print {key => 'value'}->to_json;
    #=> 'Can't call method "to_json" on unblessed reference'

UNIVERSAL::to_json provides to_json() method to all objects.
Besides, this module supports you to extend unblessed values like scalar, reference to array and reference to hash using brilliant autobox module. This feature enables you to call to_json() method directly from such values. It is optional.