AUTOLOAD और DESTROY
AUTOLOAD उन methods की calls catch करता है जो exist नहीं करतीं, और DESTROY तब चलता है जब एक object clean up होता है।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- AUTOLOAD के अंदर DESTROY handle करना भूल जाना
- $AUTOLOAD से package name strip न करना
- 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: