デストラクタがあることに少しびっくりした。
参照カウンタの成せる技かな。
#!/usr/bin/env perl use warnings; use strict; use Carp; package Foo; sub new { my ($class, $x) = @_; print "Foo::new($x)" . "\n"; bless { x => $x }, $class; } sub func { my $self = shift; print "Foo($self->{x})->func()\n"; } sub DESTROY { my $self = shift; print "Foo($self->{x})->DESTROY()" . "\n"; } package main; my $a = new Foo(1); #my $x; print "----- scope in -----\n"; { my $b = new Foo(2); $b->func(); #$x = $b; } print "----- scope out -----\n"; $a->func();
Foo::new(1)
----- scope in -----
Foo::new(2)
Foo(2)->func()
Foo(2)->DESTROY()
----- scope out -----
Foo(1)->func()
Foo(1)->DESTROY()
#!/usr/bin/env perl use warnings; use strict; use Carp; package Foo; sub new { my ($class, $x) = @_; print "Foo::new($x)" . "\n"; bless { x => $x }, $class; } sub func { my $self = shift; print "Foo($self->{x})->func()\n"; } sub DESTROY { my $self = shift; print "Foo($self->{x})->DESTROY()" . "\n"; } package main; my $a = new Foo(1); my $x; print "----- scope in -----\n"; { my $b = new Foo(2); $b->func(); $x = $b; } print "----- scope out -----\n"; $a->func();
Foo::new(1)
----- scope in -----
Foo::new(2)
Foo(2)->func()
----- scope out -----
Foo(1)->func()
Foo(2)->DESTROY()
Foo(1)->DESTROY()