2008年3月17日月曜日

Making subroutine alias with typeglob

If you assign an anonymous subroutine to lexical variable $ref, you need to use &$ref to call the subroutine. It's not cool. You can use like calling a usual subroutine if you make aliases with typeglob.
my $target = 'abcbac#ok#dddse';
my $regexp = '#(.+?)#';
*regexp_p = sub { $_[0] =~ m/$_[1]/; defined $1 and print $1; };
regexp_p($target, $regexp);

The name of typeblog that is now using become available after setting it undefined.
undef *regexp_p;

If you want to make an alias of the existing usual subroutine, do like this.
sub regexp_p_sub {
my $target = shift;
my $regexp = shift;
$target =~ m/${regexp}/;
defined $1 and print $1;
}
*regexp_p = \®exp_p_sub;
regexp_p($target, $regexp);

Apparently this sort of thing is not popular, but I was taught so much by the codes of the subroutines to create accessors in Class::Accessor. (the subroutines : _mk_accessors, follow_best_practice)

http://search.cpan.org/src/KASEI/Class-Accessor-0.31/lib/Class/Accessor.pm

I take some sort of reference and modified the above sample.
sub make_glob {
no strict 'refs';
*{ $_[0] } = sub { $_[0] =~ m/$_[1]/; defined $1 and print $1; };
}
make_glob('regexp_p');
regexp_p($target, $regexp);

0 件のコメント: