Jun 29, 2013

Inheritance in Perl

Inheritance with an Example using Perl

Inheritance:
Inheritance is nothing but inheriting methods/properties from Parent class to child class.
Inheritance is one of main pillars of Object Oriented Concepts.

Inheritance in Perl :
In Perl, inheritance is accomplished by placing the names of parent classes into a special array called @ISA
The elements of @ISA are searched left to right for any missing methods.

E.g.,
our @ISA = qw(AAA BBB);
#This represents we are inheriting from Packages AAA and BBB respectively.

 Lets define with an example as mentioned below :

Inventory.pm (Parent of Pen)
Pen.pm           (Pen inherits methods from Inventory)
main.pl            (Create instance of Pen and accessing the methods of Inventory class as well)


Inventory.pm

#!/usr/bin/perl

package Inventory;

use strict;
use warnings;
use Data::Dumper;

sub new {
    my($class)  = shift;
    my(%params) = @_;
    bless {
       "NUMBER"    => $params{"NUMBER"},
       "QUANTITY" => $params{"QUANTITY"}
    }, $class;
}

1;  


Pen.pm

#!/usr/bin/perl

package Pen;

use strict;
use warnings;
use Data::Dumper;

use Inventory;

our @ISA = qw(Inventory);    #### Inheritance

sub new {
    my($class) = shift;
    my(%params) = @_;

    #my($self) = Inventory->new(@_);
    my($self) = new Inventory(@_);

    $self->{"COLOR"} = $params{"COLOR"};
    return(bless($self, $class));
}

1;
  

main.pl

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Pen;

my $pen = new Pen(
        "NUMBER"   => "12A-34",
        "QUANTITY" => 34,
        "COLOR"    => "blue"
        );

print("The part number is " . $pen->{'NUMBER'}   . "\n");
print("The quantity is "    . $pen->{'QUANTITY'} . "\n");
print("The ink color is "   . $pen->{'COLOR'}    . "\n");
  

Output:
The part number is 12A-34
The quantity is 34
The ink color is blue


Jun 28, 2013

Package or Class Example in Perl

Packages or Classes in Perl (OOPS Concept)

Definition :
In Perl, a class is corresponds to a Package.
To create a class in Perl, we first build a package.
A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again.
They provide a separate namespace within a Perl program that keeps subroutines and variables from conflicting with those in other packages.

Rules to be followed for a module in Perl :
The module in perl in general terms means a namespace defined in a file. Certain modules are only collections of function. In perl the modules must follow the following guidelines:
- The file name of a module must the same as the package name.
- The general naming convention of naming a package is to begin with a capital letter, but not mandatory always.
- All the file name should have the extension of "pm".
- Last line of a package is 1 i.e., returning always 1 as mentioned in the example below.
- In case no object oriented technique is used the package should be derived from the Exporter class.
- Also if no object oriented techniques are used the module should export its functions and variables to the main namespace using the @EXPORT and @EXPOR_OK arrays.
The use directive is used to load the modules.

Creating/Defining Object :
To create an instance of a class (an object) we need an object constructor.
This constructor is a method defined within the package.

What is Bless : 
You create a hash object and bless the hash object to who ever calling the constructor (new method) of a package/class.

E.g.,
Blessing an object based on the parameters passed to the constructor method
my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
 bless $self, $class;

Blessing an empty object is also possible
my $self = {};
bless $self , $class

E.g.,
Package Person;
sub new {
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    bless $self, $class;
    return $self;
}
1;

Creating Instance of Object :
In order to access package level methods, you need to create object of that class and then start accessing package level variables/methods.

my $object = new Person( "David", "Johnson", 23234345);
In the above example, we are creating object of Person from main.pl, here we are passing required parameters and the constructor (new method) of Person class will return a formatted hash object.

You can even bless an empty hash object as well.        
In case of empty object, the following returns empty object
my $object = new Person();

E.g.,
use Person;
use Data::Dumper;
my $object = new Person( "David", "Johnson", 23234345);

print "\n Person Object is : " . Dumper($object);

Information Hiding : 
This should not allow the users from modifying the object data.
You should allow the users to access the core object using setter/getter methods, there by achieving hiding object data from outside the world.

Let's see the below example for better understanding :
Support.pm has defined some getter(setFirstName) and setter(getFirstName) for accessing firstName
main.pl is accessing the firstName using getter(setFirstName) and setter(getFirstName)

support.pm

#!/usr/bin/perl

package support;

use strict;
use warnings;
use Data::Dumper;

sub new
{
    my $class = shift;
    print "\nClass Name : " . $class;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "\nFirst Name is $self->{_firstName}";
    print "\nLast Name is $self->{_lastName}";
    print "\nSSN is $self->{_ssn}";
    bless $self, $class;
    return $self;
}

sub setFirstName {
    my ( $self, $firstName ) = @_;
    $self->{_firstName} = $firstName if defined($firstName);
    return $self->{_firstName};
}

sub getFirstName {
    my( $self ) = @_;
    return $self->{_firstName};
}

1;
  

main.pl

#!/usr/bin/perl
use support;

use strict;
use warnings;
use Data::Dumper;

my $object = new support( "David", "Johnson", 23234345);

# Get first name which is set using constructor.
my $firstName = $object->getFirstName();

print "\n\nBefore Setting First Name is : $firstName";

# Now Set first name using helper function.
$object->setFirstName( "Mohd" );

# Now get first name set by helper function.
$firstName = $object->getFirstName();

print "\nAfter Setting First Name is : $firstName\n";  


Output :

Class Name : support
First Name is David
Last Name is Johnson
SSN is 23234345

Before Setting First Name is : David
After Setting First Name is : Mohd 
 


Perl How to Export Methods

We have Exporter module in Perl :

Modules are packages but which has the capabilities of exporting selective subroutines/scalars/arrays/hashes of the package to the namespace of the main package itself.

So for the interpreter these look as though the subroutines are part of the main package itself and so there is no need to use the scope resolution operator while calling them.

It may do this by providing a mechanism for exporting some of its symbols into the symbol table of any package using it

There are times we want to export/expose methods or variables to other classes.

All these can be achieved by using module called "Exporter" module.

This is usually done like:
use Exporter;
our @ISA = ('Exporter');

Also we want to export only few methods instead of all methods, this can be achieved by
# Functions and variables which are exported by default
our @EXPORT = (multiply, $var1);

We might not want to export methods by default instead want to export on demand.
# Functions and variables which can be optionally exported
our @EXPORT_OK = (add);

Lets explain the same in detail with a class/package example :
support.pm package, it is exporting few methods
main.pl is making use of the exported methods/vars from support.pm package

support.pm

#!/usr/bin/perl

package support;

use strict;
use warnings;
use Data::Dumper;

use base qw(Exporter);  #which inturn equals to use Exporter; our @ISA = qw(Exporter);

#Exporting the add and subtract routine
our @EXPORT    = qw(multiply $var1);

#Exporting the multiply and divide routine on demand basis.
our @EXPORT_OK = qw(add);

our $var1 = 'global_var';

sub multiply {
  my $a = shift;
  my $b = shift;
 
  return ($a*$b);
}  

sub add {
  my $a = shift;
  my $b = shift;
 
  return ($a+$b);
}  

1;
  

main.pl

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

use support;          #Which is for EXPORT, export default ones (multiply, $val) by default 
use support qw(add);  #Which is for EXPORT_OK, export on demand (add on demand)

my $result = multiply(109,201);

print "\n Result after multiplication : " . $result;

print "\n Var from support.pm : " . $var1;

print "\n Result after addition : " . add(10,20);
  

Output:
 Result after multiplication : 21909
 Var from support.pm : global_var
 Result after addition : 30  



Delete element from Hash in Perl

You can use 'delete' command for deleting an element from an hash.
It will delete key-value pair.

Please refer to the below script:

#!/usr/bin/perl 

use strict;
use warnings;
use Data::Dumper;

my %hash = ( a => 10, b => 20, c => 30, d => 40);

print "\n Before Deleting : " . Dumper(\%hash);

delete $hash{a};

print "\n After Deleting : " . Dumper(\%hash);  

Output:

Before Deleting : $VAR1 = {
          'c' => 30,
          'a' => 10,
          'b' => 20,
          'd' => 40
        };

 After Deleting : $VAR1 = {
          'c' => 30,
          'b' => 20,
          'd' => 40
        };
  

Delete element from Array in Perl

You can use 'delete' command for deleting an element from an array.
When you delete an element from the middle of an array, that particular elements is undef (ie., not defined)

Please refer to the below program:

#!/usr/bin/perl 

use strict;
use warnings;
use Data::Dumper;

my @array = qw/10 20 30 40 50/;

print "\n Before Deleting :" . Dumper(\@array);

delete $array[2];

print "\n After Deleting :" . Dumper(\@array);
  

Output:

Before Deleting :$VAR1 = [
          '10',
          '20',
          '30',
          '40',
          '50'
        ];

 After Deleting :$VAR1 = [
          '10',
          '20',
          undef,
          '40',
          '50'
        ];
  


Execute Perl or Python or PHP online

I come across a very good site where you can run perl online and see the results.

http://www.compileonline.com/execute_perl_online.php

Advantages:
Just write the code (in the left panel) and run on the fly.
If case of any errors, it is shown on the right panel
They also prive an input.txt (in one of the tab) and practice reading/writing files
When you click on Multiple Files, it also gives support.pm, we can practice package concepts.

You can also run online Python/PHP/Java/Shell/JavaScript/HTML etc.,

Python:
http://www.compileonline.com/execute_python3_online.php

PHP:
http://www.compileonline.com/execute_php_online.php

Java:
http://www.compileonline.com/compile_java_online.php

Shell Scripting:
http://www.compileonline.com/execute_ksh_online.php

Java Script:
http://www.compileonline.com/try_javascript_online.php

HTML:
http://www.compileonline.com/try_html5_online.php

and many more on home page

http://www.compileonline.com/

Jun 11, 2013

Shift Unshift in Perl

Shift/Unshift => It works at the start of the array

Shift     => It removes element from start of an array
Unshift => It appends element to start of an array

use strict;
use warnings;

my @names = ("Foo", "Bar", "Baz");

print "\n Array : " . Dumper(\@names);

my $first = shift @names;     #Shift - removes element at the start of the array

print "$first";               #Foo
print "\n After Shift : " . Dumper(\@names);   #Bar Baz

unshift @names, "Moo";         # UnShift - adds element at the start of the array
print "\n After UnShift : " . Dumper(\@names);   # Moo Bar Baz  

Push Pop in Perl

Push/Pop      => It works at the end of the array
Push => Appends an element to end of an array
Pop  => Deletes an element from end of an array

@myNames = ('Larry', 'Curly');
push(@myNames, 'Moe');     #It adds 'Moe' at the end of the array

O/P: ('Larry', 'Curly', 'Moe')


@myNames = ('Larry', 'Curly', 'Moe');
$oneName = pop(@myNames);  #It removes 'Moe' from the end of the array

O/P: ('Larry', 'Curly')  

Delete an entry in Array and Hash in Perl

Let's discuss about deleting an element in array and hash respectively.

Deleting an element from an array:
use strict;
use warnings;

use Data::Dumper;

my @array = qw/10 20 30 40 50/;

print "\n Before Deleting :" . Dumper(\@array);

delete $array[2];

print "\n After Deleting :" . Dumper(\@array); 

Output:
Before Deleting :$VAR1 = [
          '10',
          '20',
          '30',
          '40',
          '50'
        ];

 After Deleting :$VAR1 = [
          '10',
          '20',
          undef,
          '40',
          '50'
        ];
 


Deleting an element from Hash:
use strict;
use warnings;

use Data::Dumper;

my %hash = ( a => 10, b => 20, c => 30, d => 40);

print "\n Before Deleting : " . Dumper(\%hash);

delete $hash{a};

print "\n After Deleting : " . Dumper(\%hash);

Output:
Before Deleting : $VAR1 = {
          'c' => 30,
          'a' => 10,
          'b' => 20,
          'd' => 40
        };

 After Deleting : $VAR1 = {
          'c' => 30,
          'b' => 20,
          'd' => 40
        };