Created
February 29, 2012 12:47
-
-
Save akiym/1940560 to your computer and use it in GitHub Desktop.
Perlで動的ディスパッチ/動的メソッド定義
This file contains 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
use strict; | |
use warnings; | |
# http://d.hatena.ne.jp/yuheiomori0718/20120116/1326715412 | |
package MyString; | |
use overload q{""} => \&as_string, fallback => 1; | |
sub new { | |
my ($class, $str) = @_; | |
return bless \$str, $class; | |
} | |
sub as_string { ${$_[0]} } | |
my %colors = ( | |
black => '000', | |
red => 'f00', | |
green => '0f0', | |
yellow => 'ff0', | |
blue => '00f', | |
magenta => 'f0f', | |
cyan => '0ff', | |
white => 'fff', | |
); | |
for my $color (keys %colors) { | |
my $code = $colors{$color}; | |
no strict 'refs'; | |
*{__PACKAGE__ . '::' . "in_$color"} = sub { | |
my $self = shift; | |
return qq{<span style="color: #$code">$self</span>}; | |
}; | |
} | |
package main; | |
my $str = MyString->new('Hello, world!'); | |
my $method_to_call = 'in_black'; | |
print $str->$method_to_call; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment