Monday, June 6, 2011

perl oo

perl Object Oriented:
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

adding values into INC perl

@INC array is actually array element the perl program will search for the perl modules in the program.


PERL5LIB="/usr/home";
export PERL5LIB:

This will add the path "/usr/home" to the first element of the @INC array.

To remove the content set by PERL5LIB simply use

unset PERL5LIB;


There is also a other way:
add this line before the use module lines

use lib "/usr/home";

This will also add the path to "/usr/home" temporarily to the INC path for this particular program.

perl string compare

To compare striings in perl use this simple example


#!/usr/bin/perl
#here eq must be used if you use "=" it will always return a positive value
if ( $dd eq "hello" )
{
       print "it is equal");
}
else
{
      print "it is not equal"
}

Also refer to the perl comparison  in the site for better understanding
http://linux-forum-karthik.blogspot.com/2011/06/comparison-in-perl.html