On Oct 18, Daniel Kasak said:

I've got an OO object that I want to destroy from inside the object itself.

sub destroy_self {
 my $self = shift;
 $self = undef;
}

But this doesn't work. What is the correct way of doing it?

That's because you're not getting rid of the CONTENTS of the object, you're merely undefining a variable that holds a reference to the contents.

Ordinarily, you can just wait for the object to go out of scope and it will be destroyed by Perl. However, if you want to do it when you want to, here's a sneaky way:

  sub kill_object {
    undef $_[0];
  }

Call it as

  $obj->kill_object;

and the object will be destroyed. The reason this works and '$self = undef' doesn't is because the elements of @_ act as aliases; if you operate on elements of @_ DIRECTLY, you can affect changes in the things passed to the function. Here's a more general example:

  sub trim {
    for (@_) { s/^\s+//, s/\s+$// }
  }

This trim() function doesn't *return* trimmed string, it trims the strings you sent it:

  @words = ("  this", "  and  ", " that   ");
  trim(@words);
  print "[EMAIL PROTECTED]";  # [this and that]

Of course, you can't send an ACTUAL string to trim(), because you can't modify a constant string:

  trim("  hello  ");  # run-time fatal error

--
Jeff "japhy" Pinyan        %  How can we ever be the sold short or
RPI Acacia Brother #734    %  the cheated, we who for every service
http://www.perlmonks.org/  %  have long ago been overpaid?
http://princeton.pm.org/   %    -- Meister Eckhart

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to