Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat should I do with an object that should no longer be used in Perl?
    text
    copied!<p>I am writing a class that is linked to an external resource. One of the methods is a delete method that destroys the external resource. No further method calls should be made on that object. I was thinking of setting a flag and die'ing inside of all of the methods if the flag is set, but is there a better, easier way? Something involving DESTROY maybe?</p> <p>So far, I am really liking Axeman's suggestion, but using AUTOLOAD because I am too lazy to recreate all of the methods:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; my $er = ExternalResource-&gt;new; $er-&gt;meth1; $er-&gt;meth2; $er-&gt;delete; $er-&gt;meth1; $er-&gt;meth2; $er-&gt;undelete; $er-&gt;meth1; $er-&gt;meth2; $er-&gt;delete; $er-&gt;meth1; $er-&gt;meth2; $er-&gt;meth3; package ExternalResource; use strict; use warnings; sub new { my $class = shift; return bless {}, $class; } sub meth1 { my $self = shift; print "in meth1\n"; } sub meth2 { my $self = shift; print "in meth2\n"; } sub delete { my $self = shift; $self-&gt;{orig_class} = ref $self; return bless $self, "ExternalResource::Dead"; } package ExternalResource::Dead; use strict; use Carp; our $AUTOLOAD; BEGIN { our %methods = map { $_ =&gt; 1 } qw/meth1 meth2 delete new/; } our %methods; sub undelete { my $self = shift; #do whatever needs to be done to undelete resource return bless $self, $self-&gt;{orig_class}; } sub AUTOLOAD { my $meth = (split /::/, $AUTOLOAD)[-1]; croak "$meth is not a method for this object" unless $methods{$meth}; carp "can't call $meth on object because it has been deleted"; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload