Wednesday, April 20, 2011

usage of bless function in perl

There are many chances that you may get confused with Perl Object Programming

To make the point clear let us first look at references at Perl

@friends = ("Rachael","Phoebs");
%animals = ('donald' => 'duck','mickey' => 'mouse' );


To intiaize  references to a variable use:
In case of array:
$ref  = \@friends
In case of hashes
ref = \%animals;
In case of sub-routine:
$ref=\&whoami;

Print ref ;   ---> to see refernce value

To access elements through references

print $$ref[0]  - it prints Rachael
print  $$ref{ 'mickey'}   - > it prints mouse


Having a basic idea of reference  will help you to use object oriented programming.

In perl ,object is a reference that belongs to a specific package.


method - used to associate a reference with a specific package is referred as "blessing"

constructor is merely a sub-routine that returns a reference to something blessed into a class.


To invoke the constructor in perl you can use:

$bob = Easterbunny::new();
$bob = new Easterbunny;
$bob=Easterbunny - > new();

bless function is used to change the datatype of the anonymous hash to $class.

An anonymous hash is used to hold the properties of the classs.

some key items to remember:
1)All objects are anonymous hashes which not strictly true,perhaps it should be.
2)bless function changes the data type of the anonymous hashes.
3)objects can belong to only one class at a time.
5)the -> operator is  used to call a method.


to demonstrate the bless function changes the datatype of the class:

#!/usr/bin/perl
$foo = {};
$fooref = \$ref;
print (" datatype of \$foo is " .ref($foo) . "\n");   ---> Hash here
bless ($foo,"Bar"); 
print ("datatype of \$foo is " ref($foo) ."\n");  ---->Bar here after blessing with the Bar class

output :

datatype of $foo is Hash
datatype of $foo is  Bar








No comments:

Post a Comment