Perl UNIVERSAL
Published on 30 Nov 2007Tags #Perl
All blessed references inherit from UNIVERSAL
:
-
Checking the type of a reference:
$obj->isa(TYPE) CLASS->isa(TYPE) isa(VAL, TYPE)
-
Checking for the existence of a function:
$obj->can(METHOD) CLASS->can(METHOD) can(VAL, METHOD)
-
Example for the above:
#!/usr/bin/perl use strict; use warnings; if (not Test->can('new')) { die 'do not know how to create an object of type "Test"' . "n"; } my $obj = Test->new(); if ($obj->isa('Test')) { print '$obj is a "Test"' . "n"; } if ($obj->can('print')) { print '$obj can "print"' . "n"; } package Test; sub new { my $pkg = shift; return bless {}, $pkg; } sub print { print 'Hello, world!' . "n"; } 1;