Objects जाँचना: ref, isa और can
Perl आपको बता सकता है कि एक object किस class का है और यह क्या कर सकता है।
In this page:
Objects Check करना: ref, isa, और can
ref($obj) एक blessed reference का class name return करता है। isa और can methods, जो हर class UNIVERSAL से inherit करती है, check करते हैं कि क्या एक object एक class से derived है और क्या इसके पास एक दिया गया method है। can एक code reference return करता है जिसे आप call कर सकते हैं, या अगर method exist न करे तो एक false value।
Note:
isa और can को सिर्फ real objects पर $obj->isa(Class) की तरह call करें; unknown values पर पहले Scalar::Util::blessed इस्तेमाल करें।
उदाहरण: Checking objects: ref, isa and can
use strict;
use warnings;
package Shape;
sub new { my $class = shift; return bless {}, $class; }
sub area { return 0; }
package Circle;
our @ISA = ('Shape');
sub radius { return 2; }
package main;
my $c = Circle->new;
print "ref: ", ref($c), "\n";
print "isa Circle: ", ($c->isa('Circle') ? "yes" : "no"), "\n";
print "isa Shape: ", ($c->isa('Shape') ? "yes" : "no"), "\n";
print "isa Dog: ", ($c->isa('Dog') ? "yes" : "no"), "\n";
print "can radius: ", ($c->can('radius') ? "yes" : "no"), "\n";
print "can area (inherited): ", ($c->can('area') ? "yes" : "no"), "\n";
print "can volume: ", ($c->can('volume') ? "yes" : "no"), "\n";
if (my $m = $c->can('radius')) {
print "radius via can: ", $c->$m(), "\n";
}
print "class string can: ", (Circle->can('new') ? "yes" : "no"), "\n";
# Output:
# ref: Circle
# isa Circle: yes
# isa Shape: yes
# isa Dog: no
# can radius: yes
# can area (inherited): yes
# can volume: no
# radius via can: 2
# class string can: yes
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- ref($obj) को eq से compare करना और subclasses miss करना
- undef या एक unblessed reference पर एक method call करना
- यह भूल जाना कि can एक code reference return करता है, method का result नहीं
चैप्टर सारांश
- ref एक object की class return करता है
- isa class या इसके ancestors check करता है
- can एक method check करता है
- can एक code reference return करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: