Created
December 28, 2010 08:31
-
-
Save kazeburo/757056 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| package Num; | |
| use overload | |
| '""' => \&stringfy, | |
| '0+' => \&numeric; | |
| sub new { | |
| my ($class, $value) = @_; | |
| bless \$value, $class; | |
| } | |
| sub stringfy { | |
| my $self = shift; | |
| qq!"$$self"!; | |
| } | |
| sub numeric { | |
| my $self = shift; | |
| $$self; | |
| } | |
| package OW; | |
| use strict; | |
| use warnings; | |
| use base qw/Exporter/; | |
| use Data::Dumper; | |
| use Scalar::Util qw/blessed/; | |
| our @EXPORT = qw/ow/; | |
| use overload | |
| '""' => \&stringfy, | |
| '0+' => \&numeric; | |
| sub ow { | |
| __PACKAGE__->new(shift); | |
| } | |
| sub new { | |
| my ($class, $value) = @_; | |
| bless \$value, $class; | |
| } | |
| sub stringfy { | |
| my $self = shift; | |
| my $value = $$self; | |
| if ( blessed($value) && (my $stringify = overload::Method( $value, '""' )) ) { | |
| $value = $stringify->($value); | |
| } | |
| dumper($value); | |
| } | |
| sub numeric { | |
| my $self = shift; | |
| my $value = $$self; | |
| if ( blessed($value) && (my $numeric = overload::Method( $value, '0+' )) ) { | |
| $value = $numeric->($value); | |
| } | |
| dumper($value); | |
| } | |
| sub dumper { | |
| my $value = shift; | |
| if ( defined $value && ref($value) ) { | |
| local $Data::Dumper::Terse = 1; | |
| local $Data::Dumper::Indent = 0; | |
| $value = Data::Dumper::Dumper($value); | |
| } | |
| $value; | |
| } | |
| 1; | |
| package main; | |
| use URI; | |
| use Scalar::Util qw/dualvar/; | |
| my $uri = URI->new("http://yahoo.co.jp");; | |
| printf "1: %s\n", OW::ow($uri); | |
| printf "2: %d\n", OW::ow($uri); | |
| printf "3: %f\n", OW::ow($uri); | |
| printf "4: %o\n", OW::ow($uri); | |
| my $num = Num->new(200); | |
| printf "1: %s\n", OW::ow($num); | |
| printf "2: %d\n", OW::ow($num); | |
| printf "3: %f\n", OW::ow($num); | |
| printf "4: %x\n", OW::ow($num); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment