読者です 読者をやめる 読者になる 読者になる

kopug memo

名古屋で働くとあるWebエンジニアの覚書。

Recursive Method

Perl
package RecursiveMethod;

use strict;
use warnings;
use Carp;
use vars qw/$AUTOLOAD/;

sub new {
    my $class    = shift;
    my $args_ref = shift || {};
    bless $args_ref,$class;
}

sub AUTOLOAD {
    my $self = shift;

    my ($method) = ( $AUTOLOAD =~ /.*::(.+)$/ );

    croak "Can't locate object method ". $method .' via package "'. __PACKAGE__ .'"'
        if !exists $self->{$method};

    return (ref $self->{$method} eq 'HASH')
           ? __PACKAGE__->new( $self->{$method} )
           : $self->{$method};
}

1;

呼出し元

#! perl -w

use strict;
use CGI;
use Data::Dumper;

my $new_args_ref
    = {
        name => 'kopug',
        hoge => {
                    foo => CGI->new,
                    boo => {
                                dodo => 'DoDo'
                            },
                }

      };

my $r_obj = RecursiveMethod->new( $new_args_ref );

warn Dumper $r_obj->hoge()->foo();

実行結果

$VAR1 = bless( {
                 '.parameters' => [],
                 '.charset' => 'ISO-8859-1',
                 '.fieldnames' => {},
                 'escape' => 1
               }, 'CGI' );

まちがったメソッドを使った場合。

warn Dumper $r_obj->hoge()->foo222();

実行結果

Can't locate object method foo222 via package "RecursiveMethod" at hoge.pl line 21