I am wondering about some weird behavior I am seeing and am wondering if there is anybody who might have an explanation.

I have below, three instantiations of objects that upfront seem like they should all have the same result. I am attempting to tie the object the scope of the "if" block and have the DESTROY method called as the if block leaves scope. The first two methods work properly, but the third does not. You cannot access $obj outside any of the "if" blocks - even after the third block - but the object does not DESTROY after the final block -- only when the program stops running.

Can anybody explain what is happening here, and if so, is the file still in scope somewhere in the internals or what? I have tried this on older perls as well with the same result.

#! /usr/bin/perl -w package MyPack; use strict; sub new { return bless {},__PACKAGE__; } sub DESTROY { print "I'm destroyed\n"; } print "[$]]\n\n"; if( 1 ){ my $obj = MyPack->new(); print "Inside the IF (1)\n"; } print "Outside the IF (1)\n"; print "\n"; if( defined(my $obj = MyPack->new() ) ){ print "Inside the IF (2)\n"; undef $obj; } print "Outside the IF (2)\n"; print "\n"; if( defined(my $obj = MyPack->new() ) ){ print "Inside the IF (3)\n"; } print "Outside the IF (3)\n";

This prints out:
[5.006] Inside the IF (1) I'm destroyed Outside the IF (1) Inside the IF (2) I'm destroyed Outside the IF (2) Inside the IF (3) Outside the IF (3) I'm destroyed




my @a=qw(random brilliant braindead); print $a[rand(@a)];

In reply to Object scope and DESTROY by Rhandom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.