challenge メソッド名一覧の表示

リフレクション系のお題の続編です。

「ある与えられたオブジェクトtargetのメソッドのうち、 "test_"で始まるものをすべて呼びだす」というコードを書いてください。 引数に関しては都合のいいように仮定して構いません(全部0個、など)。

メソッドという概念がない言語の場合は、 「複数の関数への参照を持っているようなオブジェクト(たとえばパッケージとかモジュールとか)から"test_"で始まる関数をすべて呼び出す」と読み替えても構いません。

Posted feedbacks - Perl

CPANだよりですが。。。^^;
1
2
3
4
5
6
7
8
9
#!/usr/local/bin/perl

use target;
use Class::Inspector;

foreach my $f (@{(Class::Inspector->functions( 'target' ))[0]}) {
    print eval{target->$f()} if ($f =~ /^test_.+$/);
}
exit;

Class::Inspector, Scalar::Util使用版
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/perl

package Foo;

{
    no strict 'refs';

    for my $method (qw/foo bar baz test_foo test_bar test_baz/) {
        *{"Foo::$method"} = sub {
            print $method . "\n";
        };
    }
}

sub new {
    bless {} => shift;
}

package main;

use strict;
use warnings;

use Scalar::Util qw(blessed);
use Class::Inspector;

sub call_methods_by_regex {
    my ($target, $regex) = @_;

    return unless (my $class = blessed($target));
    return unless (ref $regex eq 'Regexp');

    my @methods = grep { /$regex/o } @{Class::Inspector->methods($class, 'public')};

    for my $method (@methods) {
        $target->$method();
    }
}

call_methods_by_regex(Foo->new, qr/^test_/);

CPANに頼らない版
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/perl

package Foo;

{
    no strict 'refs';

    for my $method (qw/foo bar baz test_foo test_bar test_baz/) {
        *{"Foo::$method"} = sub {
            print $method . "\n";
        };
    }
}

sub new {
    bless {} => shift;
}

package main;

use strict;
use warnings;

{
    no strict 'refs';
    sub call_methods_by_regex {
        my ($target, $regex) = @_;
        my $class = ref $target;

        return if (!$class || $class =~ /^(SCALAR|ARRAY|HASH|CODE|GLOB|LVALUE)$/);
        return unless (ref $regex eq 'Regexp');

        my @methods = 
            grep { *{${$class . "::"}{$_}}{CODE} } 
            grep { /$regex/o } 
                keys %{$class . "::"};
        
        for my $method (@methods) {
            $target->$method();
        }
    }
}

call_methods_by_regex(Foo->new, qr/^test_/);

Index

Feed

Other

Link

Pathtraq

loading...