← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 7 of 7

AUTOLOAD और DESTROY

AUTOLOAD उन methods की calls catch करता है जो exist नहीं करतीं, और DESTROY तब चलता है जब एक object clean up होता है।

In this page:

  1. AUTOLOAD और DESTROY

AUTOLOAD और DESTROY

जब एक method न मिले, Perl class hierarchy में AUTOLOAD नाम का एक subroutine ढूंढता है और package variable $AUTOLOAD को missing method के full name पर set करता है। आपको DESTROY के लिए early return करना चाहिए, क्योंकि Perl भी AUTOLOAD के जरिए DESTROY call करता है अगर कोई defined न हो। जब किसी object का last reference गायब हो जाए DESTROY automatically call होता है, जो cleanup के लिए useful है।

Note: अगर आप AUTOLOAD इस्तेमाल करते हैं एक empty sub DESTROY {} define करें, ताकि object destruction AUTOLOAD से न गुज़रे।

उदाहरण: AUTOLOAD and DESTROY

perl
use strict;
use warnings;

package Flexible;
our $AUTOLOAD;

sub new { my $class = shift; return bless { color => "red", size => 5 }, $class; }

sub AUTOLOAD {
    my $self = shift;
    my $name = $AUTOLOAD;
    $name =~ s/.*:://;
    return if $name eq 'DESTROY';
    die "No method $name\n" unless exists $self->{$name};
    return $self->{$name};
}

package Tracked;
sub new { my ($class, $name) = @_; print "creating $name\n"; return bless { name => $name }, $class; }
sub DESTROY { my $self = shift; print "destroying $self->{name}\n"; }

package main;

my $f = Flexible->new;
print "color: ", $f->color, "\n";
print "size: ", $f->size, "\n";
eval { $f->weight };
print "error: $@";

{
    my $t = Tracked->new("temp");
    print "inside block\n";
}
print "after block\n";

# Output:
# color: red
# size: 5
# error: No method weight
# creating temp
# inside block
# destroying temp
# after block
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. AUTOLOAD के अंदर DESTROY handle करना भूल जाना
  2. $AUTOLOAD से package name strip न करना
  3. cyclic data structures में DESTROY की exact timing पर depend करना
चैप्टर सारांश
  • AUTOLOAD missing methods handle करता है
  • $AUTOLOAD पूरा method name hold करता है
  • जब last reference चला जाए DESTROY चलता है
  • AUTOLOAD calls से बचने के लिए एक empty DESTROY define करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.