http://www.perlmonks.org?node_id=341161


in reply to Lexicals in if() scope gotcha!

  1. This is not just an issue with "if" it also happens with "for" (but not foreach, or while)...
    #!/usr/bin/perl print "foreach...\n"; foreach (Foo->new) {} print "after foreach\n"; print "while...\n"; while (my $object = Foo->new && 0) {} print "after while\n"; print "for...\n"; for (my $object = Foo->new; 1 < 0; ) {} print "after for\n"; package Foo; sub new { my $self = bless {},shift; print "CREATED $self\n"; $self } sub DESTROY { print "DESTROYED $_[0]\n" } __END__ bester:~/tmp> monk.pl foreach... CREATED Foo=HASH(0x22494) DESTROYED Foo=HASH(0x22494) after foreach while... CREATED Foo=HASH(0x305f0) DESTROYED Foo=HASH(0x305f0) after while for... CREATED Foo=HASH(0x22494) after for DESTROYED Foo=HASH(0x22494)
  2. This is why you should allways head the immortal words of perltoot...
    Perl's notion of the right time to call a destructor is not well-defined currently, which is why your destructors should not rely on when they are called.