[perl] 続・初めてのPerl 第14章 「オブジェクトに関する高度なトピックス」
練習問題の回答をメモ。…したいところだったけど、全然思いつかなくて答えを見てしまった。一応、答えをそのまま載せておく。
ex14-1
#!/usr/bin/perl use strict; use warnings; { package MyDate; use vars qw($AUTOLOAD); # our $AUTOLOAD と同じ(ラクダ本 p.1022) use Carp; my %Allowed_methods = ( date => 3, month => 4, year => 5, ); my @Offsets = qw(0 0 0 0 1 1900 0 0 0); sub new { bless {}, $_[0] } sub DESTROY {}; sub AUTOLOAD { our $method = $AUTOLOAD; $method =~ s/.*:://; unless (exists $Allowed_methods{$method}) { carp "Unknown method: $AUTOLOAD"; return; } my $slice_index = $Allowed_methods{$method}; return (localtime)[$slice_index] + $Offsets[$slice_index]; } } MyDate->import; my $date = MyDate->new; print "The date is ", $date->date, "\n"; print "The month is ", $date->month, "\n"; print "The year is ", $date->year, "\n";
ex14-2
# MyDateパッケージ中のコード sub UNIVERSAL::debug { my $self = shift; printf "[%s] %s\n", scalar localtime, join '|', @_; } # テスト $date->debug('Hoge', 'Fuga');
反省点
この章は全体的によく理解していないので、あとで読み返そう。
p.190 の *{$AUTOLOAD} とかって何だろう?