Skip to content

Instantly share code, notes, and snippets.

@akiym
Created February 29, 2012 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akiym/1940560 to your computer and use it in GitHub Desktop.
Save akiym/1940560 to your computer and use it in GitHub Desktop.
Perlで動的ディスパッチ/動的メソッド定義
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