2013年2月12日火曜日

開発環境

『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也田中 慎司吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9)の14章(オブジェクトに関する高度なトピックス), 14.7(練習問題)2.を解いてみる。

その他参考書籍

2.

コード(BBEdit)

sample.pl

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;

sub UNIVERSAL::debug {
    my $self = shift;
    print localtime . ": @_\n";
}
{
    package MyDate;
    use Carp;
    my %methods = qw(day 3 month 4 year 5);
    my @offset = qw(0 0 0 0 1 1900);
    sub new {
        my $class = shift;
        bless {}, $class
    }
    sub DESTROY {}
    
    sub AUTOLOAD {
        our $AUTOLOAD;
        (my $method = $AUTOLOAD) =~ s/.*:://s;
        unless (exists $methods{$method}){
            carp "メソッド名($AUTOLOAD)がわからない";
            return;
        }
        my $i = $methods{$method};
        (localtime)[$i] + $offset[$i];
    }
}

my $date = MyDate->new;
# AUTOLOADよりUNIVERSAL(基底クラスみたいなもの)
$date->debug("Hello, World!");

入出力結果(Terminal)

$ ./sample.pl
Tue Feb 12 17:24:28 2013: Hello, World!
$

0 コメント:

コメントを投稿