UNIVERSAL Package in Perl Programming
UNIVERSAL is a built-in package in Perl 5. It can also be thought of as a base class in which the derived classes can implicitly inherit or override. It offers several default methods like
DOES(). The UNIVERSAL class cannot show in the package’s @ISA variable. Other methods can also be added to the UNIVERSAL class through Perl or XS code. There is no need to include ‘use UNIVERSAL‘ statements in code to make use of the above-mentioned methods in the program.
It returns the value of the $VERSION variable of the suitable class or package. This method can take a version number as an optional parameter. In case, the queried $VERSION is not greater than or equal to the parameter, this method throws an exception.
Let’s consider a module Dog of version 2.0
2.0 2.0 2.0 2.0 Dog version 3 required--this is only version 2.0 at /home/4c09f6973dc56e8a558b8be499a040bb.pl line 32.
DOES() method checks whether a class or an object performs a particular role or not. When the name of the role is passed to this method and if it performs the specified role, then it returns true(1) otherwise it returns false(0). The role can be thought of as a collection of behavior shown by a class.
Let’s consider modules/classes Dog and animal
1 1 1
can() method accepts the method’s name as a string. It returns a reference to the existing function that implements this method or else it returns a false value. This method can be called on a class, object, or a package.If can($classname) returns true, it means that a class having name $classname exists. This method only checks the existence of a class and does not comment on its usability.
Let’s consider a class Dog with a method named bark, a reference to this method can be made as follows:
Use of uninitialized value in say at /home/fdfdd52de0b7348de191b3d9be3cb44f.pl line 11. CODE(0x1fc3168)
can() can also be used to check if a package has successfully implemented a specific function or method or not.
isa() method accepts the name of a class or the name of a built-in type as a string. It can be called on a class method, an instance method, or an object. It returns a true if a specified class or object is derived from the package, or if it is a blessed reference to the given type.
Suppose $doggy is an object(a hash reference blessed into the Dog class, which inherits from the Animal class):
Please Login to comment...