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

nazolabo

なぞさんのブログ

perlのお勉強

perl

test.pl

print "application begin\n";

use Sample2;

print "application global\n";

my $s = Sample2->new('hoge');
$s->say('foo');

my $s2 = Sample2->new('fuga');
$s2->say('bar');

print "application end\n";

Sample.pm

package Sample;

BEGIN {
    print "package Sample BEGIN\n";
}

END {
    print "package Sample END\n";
}

print "package Sample global\n";
my $log = 'a';

sub new {
    my ($pkg, $data) = @_;

    print 'Sample constructor: '.$data."\n";

    bless {
        data => $data,
    }, $pkg;
}

sub say {
    my $self = shift;
    my $msg = shift;

    print 'Sample log: '.$log."\n";
    print 'Sample data: '.$self->{data}."\n";

    print 'Sample say: '.$msg. "\n";

    $log = $msg;
}

1;

Sample2.pm

package Sample2;
use Data::Dumper;

use base qw(Sample);
# our @ISA = 'Sample';

BEGIN {
    print "package Sample2 BEGIN\n";
}

END {
    print "package Sample2 END\n";
}

print "package Sample2 global\n";
my $log = 'b';

sub new {
    my ($pkg, $data) = @_;

    print 'Sample2 constructor: '.$data."\n";

    bless {
        data => $data,
    }, $pkg;
}

sub say {
    my $self = shift;
    my $msg = shift;

    $self->SUPER::say($msg);

    print 'Sample2 log: '.$log."\n";
    print 'Sample2 data: '.$self->{data}."\n";

    print 'Sample2 say: '.$msg. "\n";
}

1;

結果

package Sample BEGIN
package Sample global
package Sample2 BEGIN
package Sample2 global
application begin
application global
Sample2 constructor: hoge
Sample log: a
Sample data: hoge
Sample say: foo
Sample2 log: b
Sample2 data: hoge
Sample2 say: foo
Sample2 constructor: fuga
Sample log: foo
Sample data: fuga
Sample say: bar
Sample2 log: b
Sample2 data: fuga
Sample2 say: bar
application end
package Sample2 END
package Sample END

なんとなくわかった気がする!