Finding the length of an array and a hash

Learn PerlDetermining the length of an array and a hash

If you are working on Perl, then you will need to find the length or size of an array, hash, and array/hash elements very often.
Meaning of Size or length depends upon for which context you are talking about.  Generally it means the number of characters in a string, or the number of elements in an array/hash.
But, if you are using Unicode characters then the number of characters in a string may be different to the number of bytes in the string. So the in-built function length may give different result for different context.

We will see it by using different examples based on different problems:

Example 1. Finding length() of string
To determine the number of characters in an expression use the length() function:
    [perl]#!/usr/bin/perl
    use strict;
    use warnings;
 
    my $name = 'Jassi';
    my $size = length($name);
 
    print "$size\n";
    exit 0;[/perl]
This example prints the number of characters in the string $name:
    5

Example 2. Find the bytes used by string using length()
What, if you want to know the bytes occupied by the string not the characters it holds?  This may not matter if  you are using ASCII characters but it may, if you are using Unicode characters.
By default the length() function returns the number of characters. You can tell it to return the number of bytes by specifying use bytes; in the program as in this example:
  [perl]  #!/usr/bin/perl
     use strict;
    use warnings;
 
    my $char = "\x{263a}";    # A smiley face
    {
         use bytes;
        my $byte_size = length($char);
        print "Bytes: $byte_size\n";
        no bytes;
    }
    # Character size here
    my $size = length($char);
    print "Chars: $size\n";
     exit 0;[/perl]
This outputs:
    Bytes: 3
    Chars: 1
 
Note: either use closure or whenever you use “use bytes” try to use “no byets” once you are done

Number of element in an array
Example 3: using array’s last index
In Perl you can determine the last element of an array easily ($#array_name) and add 1 to it to find the number of elements in that array.
   [perl] #!/usr/bin/perl
    use strict;
    use warnings;

my @alien_members = qw(jassi Ritesh Ranjan som Santosh);
    my $size = $#alien_members + 1;
    print "$size\n";
    exit 0;[/perl]
This gives us:
    5
Example 4.  Using scalar context of an array
If you assign an array to a scalar variable, it will return the number of elements of that array:
  [perl]  #!/usr/bin/perl
     use strict;
    use warnings;
 
    my @alien_members = qw(jassi Ritesh Ranjan som Santosh);
    my $size = @alien_members;
 
    print "$size\n";
    exit 0;[/perl]
This gives us:
    5
Apart from being confusing to read, this method can lead to some easy mistakes. For example, consider the following program:
   [perl] #!/usr/bin/perl
     use strict;
    use warnings;
 
     my @alien_members = qw(Jassi Ritesh Ranjan som Santosh);
    print "@alien_members\n";
    print @alien_members."\n";
     exit 0;[/perl]
What would you expect it to print?
Each array elements to a new line like
Jassi
Ritesh
Ranjan …
Nope it would print
Jassi Ritesh Ranjan som Santosh
5
When double-quotes included, it treats arrays differently. The double-quotes cause Perl to flatten the array by concatenating the values into a string. So behind the stage, something like this happened.
“Join each array element by space and assign it to a scalar variable. So it became a string.” It is something like $size = “@alien_members”; which will differ from $size = @alien_members;

try to print these two statements and see the difference.
 But check second print output. Isn’t it strange?

Example 5. Arrays: never use length() to find the number of elements in an array.
You have seen  the use of length at Example#1 but still If you try to use the length() function on an array, it won't give you the desired output.
    [perl]#!/usr/bin/perl
 
    use strict;
    use warnings;
 
    my @alien_members = qw(Jassi Ritesh Ranjan som Santosh);
    my $size = length(@alien_members);
     print "$size\n";
    exit 0;[/perl]
The output is not what you thought:
    1
This is because the length() function requires a scalar, so the array is forced into scalar context.
And we saw already (example 4) that an array in scalar context already gives us the length. The example above is giving us the length of the length i.e. the length of 5 is 1. Hope it makes sense!

Example 6. Finding the number of elements using scalar() function
No doubt that Example 3 and 4 are correct but they aren't much clear and friendly to use in our program (readability problem you can say). Perl has the scalar() function which forces the array into scalar context which will give you the length of an array (even hash too):
   [perl] #!/usr/bin/perl
 
    use strict;
    use warnings;
 
    my @alien_members = qw(Jassi Ritesh Ranjan som Santosh);
    my $size = scalar(@alien_members);
 
    print "$size\n";
    exit 0;[/perl]
This also gives us the correct answer:
    5

Example 7. Finding the number of elements in a hash
Sometimes you will also want to have the number of elements of a hash. This is easily done using the keys() function to return the keys as an list, and the scalar() function to return how many keys there are (it is very common question in interviews too):
  [perl]  #!/usr/bin/perl
 
    use strict;
    use warnings;
 
    my %alien_members_rank = (
        Jassi => 1,
        Ritesh   => 2,
        Ranjan   => 3,
        Somnath    => 5,
        Santosh => 4
    );
    my $size = scalar(keys %alien_members_rank);
 
    print "$size\n";
    exit 0;[/perl]
The output of this program is:
    5
Note: it will not give 10 as you might have thought in context of an array. It can give you no of keys elements and then you can just multiply it by 2 😀

For more details on these functions, see also
    perldoc -f length
    perldoc -f scalar
    perldoc bytes
  
 

What is Hibernate and how it works – a minimal introduction

Hibernate LogoWhat is Hibernate and how it works – a minimal introduction

During my post graduations we had to make a project based on the requirement, at that time I heard about a word hibernate. But at that time I was not so much curious about it. I only know that it is a kind of framework. My friends was used it in their project also but I was not aware about it so I use my own Java coding for all stuff.

But when I joined an organization I came to know that here also we are using hibernate but now the situation was very difficult because I did not know A, B, C… of it. But my senior level was very cooperative and they help me a lot to overcome from the situation. So now I want to share my knowledge with you people so that in future you will not face this problem. So let’s start with the basic question what, when, why and how?

What is Hibernate?

Hibernate is a free, open source Java package that makes it easy to work with relational databases. It provides a query service for Java. Hibernate lets you develop independent classes following common Java idiom – including association, inheritance, polymorphism, composition and the Java collections framework. Hibernate is basically used with J2EE (Java web application).

It is a very popular open source technology which fits well both with Java and .NET technologies. The Hibernate 3.0 core is 68,549 lines of Java code. Hibernate maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduce the development time. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans. Hibernate is free software that is distributed under the GNU Lesser General Public License.
Source: wikipedia

When Hibernate?

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission was to simply offer better capabilities than EJB2(Enterprise Java beans) by simplifying the complexities and allowing for missing features. Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release.

JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate. On 9th Feb 2012 they have released a stable version of hibernate as Hibernate 4.1 final. It is developed in Java language so it uses JVM as a platform for the execution.

Why Hibernate?

It is the most important question that why we need hibernate into our application? So let’s discuss it in very simpler way. We know that when we develop any application, at that time for storing our data we required a database.

For example we are making a web base application for the Post-Office and here we have to keep track of all the information related to post, money order, courier etc. For the information storage point of view we use a MySQL as a backend database and we have code all things into a Java class like how to add data into database or how to perform operation on that data base. Now when we are going to deliver the product (i.e. our application) suddenly client requirement got changed and now they want ms access as their database because it is freely available and it can be easy to understand.

Can you imagine the situation now? You have a limited amount of time and you have to change your each and every class which is dealing with the database and the worst thing is that now you have to change all 50 files because it is a live application (this number can be 5000 also depend upon the scenario) . To handle this kind of situation hibernate came into picture. Hibernate provide an API (Application programming Interface) with all build in functions like insert (), delete (), update () etc. It also provides persistence architecture for a code (each class is independent). Here we follow a standard hibernate architecture in which we use xml for all the configuration settings.

 

How It Works?

Hibernate does not get in your way nor does it force you to change the way your objects behave. They do not need to implement any interfaces in order to become persist. All you need to do is create an XML "mapping document" telling Hibernate the classes you want to be able to store in a database, and how they relate to the tables and columns in that database, and then you can ask it to fetch data as objects, or store objects as data for you. At runtime, Hibernate reads the mapping document and dynamically builds Java classes to manage the translation between the database and Java program.

Now there is one question related to hibernate which was asked to me during my campus interview but at that time I was not able to answer it. Let’s find the answer

What is dirty checking?

Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. An important note here is, Hibernate will compare objects by value, except for Collections, which are compared by identity. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates.

Now I will discuss an example for a simple Java application, if you have basic knowledge in Java and JDBC (Java Database Connectivity), then you will understand it comfortably.

Suppose you have to make an application which will maintain records of the entire employee present in your office. So we will do it in the following way

 

 

Simple Design pattern to follow

Review on Modern Perl by Chromatic

Modern Perl by ChromaticWhat is Perl

Perl is the Swiss Army knife for scripting languages (rather call it programming language): powerful and adaptable. It was first developed by Larry Wall, a linguist working as a systems administrator for NASA in the late 1980s, as a way to make report processing easier.

Since then, it has moved into a large number of roles: automating system administration, acting as glue between different computer systems; and, of course, being one of the most popular languages for CGI programming on the Web.

For more information on Basic introduction on Perl, please click here
We have posted a small post on “Applications based on Perl”.

Why Modern Perl (2011-2012 edition)?

According to author Chromatic  “When you have to solve a problem now, reach for Perl. When you have to solve a problem right, reach for Modern Perl.”

There are lots of books available on Perl in the market then why and how it is unique and very popular amongst Perl programmers?
The reason is very simple , it’s author Chromatic is well renowned face over the Perl community and this book covers various features that are introduced in 5.10,5.12 and 5.14 and it got released on February,2012

Its list of contents looks very promising to me. No matter who you are, a novice in Perl or an expert; this book has something new, interesting and informative contents for you.

First three chapters deal with Perl Philosophy, its community and Basics of Perl Language. The contents are very informative and full summary on what you can achieve through Perl. You can start writing simple Perl code just after reading first three chapters too!

Next three chapters on Operators, Functions and Regular Expression will make you almost a Perl programmer within no time. If you don’t want to use object oriented Perl, then You will find yourself a comfortable programmer in Perl’s zone. But Perl’s power can’t be judged by stopping there. So next few chapters will show you the real implementation and object Oriented Perl

The next three chapters deal with Perl objects, style and efficacy and managing real Programs. These chapters will teach you

  • How to use Object Oriented concept effectively in Perl
  • Moose and Perl features
  • Pragmas, exceptions
  • How to maintain large programs
  • How to write effective Perl programs
  • How to use testing module
  • How to use file handling things and other fundamental things like overloading, taint etc

Then last three chapters deal with some exceptional topics which other authors or programmers avoid usually. Chromatic has explained and portrayed these things beautifully. He has explained

  • Syntax  like handling $self, named parameters, handling main, Global variables etc
  • What to avoid while writing Perl programs like barewords, prototypes etc
  • Missing defaults like strict, warnings, autodie etc.

Who is Chromatic

Well I put a small review on Modern Perl and praise author many times. Now who is Chromatic ?
He is a writer and free software programmer from USA. He is the author of many other popular books like

  • Extreme Programming Pocket Guide
  • Perl Hacks
  • Co-author of “Perl Testing: Developer’s Notebook”
  • Noted contributor to “The Art of Agile Development”

He has contributed to CPAN, Perl 5, Perl6 and Parrot too. He was the project secretary of Perl6 and Parrot Foundations too. He is the core developer for Parrot – an open source virtual machine created I n 2008.

From where we can buy it or download it

  • You can buy it from Amazon or Powells or Barnes and Noble book store.
  • You can download its electronic version in A4 or letter format too.
  • Get all the details about download options from Onyx Neon Press
  • You can download it from our website too!

Rating for Modern Perl (4.5/5)

I would recommend this book for all Perl enthusiasts. If you wish to start a career in Perl programming or you are a beginner in Perl Programming then just read its first three chapters and decide ahead. Check our other books recommendation below.

For intermediate and Advanced level Perl Programmers, it’s a must read book.

It would be really nice if it would have shown some real example with screenshots and output.

Other books on Perl

How to find the list of installed modules in Perl

This is one of the questions asked in many Perl related job interviews. See the question here: http://www.aliencoders.org/content/interview-questions-perl-freshers-and-experienced
There will be some situations when you will need to know about installed modules, its version or you may need to check if required module is installed or not with mentioned version or higher than that.

Here are few ways through which you can achieve the result that I found over the internet from different websites.

1. To list all installed Perl modules using perl script

[perl]
#!/usr/bin/perl   #change the path  with your perl location
use strict;
use warnings;
use ExtUtils::Installed;  # By default this module will be available in Perl

my $instmod = ExtUtils::Installed->new();
foreach my $module ($instmod->modules()) {
    my $version = $instmod->version($module) || “Version Not Found.”;
    print “$module version=$version \n”;
}
[/perl]

2. To list installed Perl modules using command line in Linux box

Try instmodsh command in linux box
and then type l to list modules or m to give particular module name or q to quit

[code] $ instmodsh[/code]

Output:
[code]Available commands are:
l            – List all installed modules
m    – Select a module
q            – Quit the program
cmd?[/code]
At cmd? prompt type l to list all installed modules:
[code]cmd? l[/code]
Output:
[code]Installed modules are:
Archive::Tar
CPAN
Compress::Zlib
MIME::Lite
Module::Build
Net::Telnet
PAR::Dist
Perl
Spiffy
Test::Base
Test::Simple
XML::Simple
cmd?
[/code]

This command itself is a perl script that use ExtUtils::Installed module. Try following command to see its source code:
[code]$ vi $(which instmodsh)[/code]
For more details, visit this link: http://perldoc.perl.org/instmodsh.html

3. To compare and check installed Perl modules with respect to given modules with its version

[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @modules = ([‘SOAP::Lite’, 0.50],
           [‘IO::Socket’, 0],
           [‘HTML::Parser’, 3.26],
           [‘LWP’, 5.65],
          );

print “\n”,
      “==========================\n”,
      “Testing for the given  Perl modules\n”,
      “===========================\n”;
      
    for my $arr_ref (@modules) {
        my($mod, $ver) = @$arr_ref;
        print “$mod” . ($ver ? ” (version >= $ver)” : “”) . “\n”;
        
        eval(“use $mod” . ($ver ? ” $ver;” : “;”));
        if ($@) {
            my $msg = $ver ?
                      “\tEither it doesn’t have $mod installed,\n” .
                      “\tor the version that is installed is too old.\n” :
                      “\tIt does NOT have $mod installed.\n”;
            print “$msg\n”;
        }
        else {
            print “\tYour system has $mod installed ” .
                  “with version @{[ $mod->VERSION ]}\n\n”;
        }
    }

print “Module Testing Done!\n”;
[/perl]

Note: If you are putting module name dynamically, then use  @{[ $mod->VERSION ]} for version number
else $Module-Name::VERSION ex: $SOAP::Lite::VERSION

[perl]
print “SOAP::Lite Version is “. $SOAP::Lite::VERSION.”\n”;
#or
 print “$mod version is @{[ $mod->VERSION ]} \n”;
 [/perl]

4. To list Perl modules that comes preinstalled with the standard Perl package and installed from outside
[perl]
perldoc perlmodlib #lists all the modules that come with standard Perl package already
perldoc perllocal #lists all modules that is installed from outside
[/perl]
Both modules reveal lots of information about each installed modules like installation date, directory, module version etc.

Person who founded C and UNIX (Dennis Ritchie) is no more

Dennis RitchieI can’t even imagine that I would get a job if there would be no UNIX, no Linux, no Windows, no graphical application, no sound driver, no GUI based tools, no programming languages and still we would be struggling with binary and machine level language.  There would not be computerized electronic gadgets no iPhone, iPad etc.

Thanks to Dennis Ritchie who not only founded C programming language and co-founded UNIX with Ken Thompson which made network sharing easier, but gave birth to many successor languages like C++, Java, Perl and many more high level languages but made our life more smooth and technologically advanced.

He died on 12th October 2011 at the age of 70. He was very famous respected computer hacker (computer genius literally). His contribution will always be remembered and implemented till we will use computer or computing based tools. He was also known as drm (Dennis MacAlistair Ritchie)

Very few people know that  Dennis Ritchie is the author of the  “C programming language- K&R style 1st and 2nd edition” . But his favorite language was Alef which is the main language of Plan9 O.S , developed by Ken Thompson and Bell Labs.

Ritchie graduated from Harvard University with degrees in physics and applied mathematics. In 1967, he began working at the Bell Labs Computing Sciences Research Center, and in 1968, he received a PhD from Harvard under the supervision of Patrick C. Fischer

 

His favorite quotations were:

  •  "UNIX is very simple, it just needs a genius to understand its simplicity."
  • "C is quirky, flawed, and an enormous success”

There are many things to write about him and his contributions. I would just point out a few.

Just Imagine the world without Ritchie’s C. Software fields and all technical developments in our field would not be possible K&R C by Ritchieif he would not have developed C. Many many thanks to you Dennis for such a sophisticated and powerful language which is still at top 5 list of most demanding programming languages by IT world.

  • C is the first language which is being taught to any First year engineering students. 
  • C is the mother of all higher level languages and still I remember that whatever language we study, we compare it with C syntax first.  PHP, Perl, C#, C++, Python, JavaScript, Java are some influenced programming languages through C.
  • Unix based operating systems where it’s Linux, Mac OSx  etc written in C only.
  • All the embedded systems, mobile device based O.S. and tools are mostly written in C.
  • Windows O.S. is having more than 60% code in C.
  • Android (very famous now in mobile devices) and Symbian OS  are written in C
  • MySQL, Oracle, PHP, nmap, snort, Wireshark, Nessus (Network scanner tools), GIMP (free image editor), Apache HTTP server,  are few famous tools written in C
  • GTK+ a toolkit used for creating graphical user interfaces is written in c.
  • C is suitable for writing programs which requires lots of computations. MATLAB and MATHEMATICIA are two such widely used software
  • Firefox is  written using C,C++, JavaScript.

Unix is an operating systems which was developed in 1969 by Ken Thompson, Brian Kernighan , Dennis Ritchie which was first written in assembly language , later in 1973 it was fully recoded in C.
Unix based servers are being used in almost every field, whether its workstation, personal computer, mobile devices, embedded systems etc.  Fedora, Debian, Mac OS,  Ubuntu etc are UNIX based O.S.

He was awarded with the following awards:

Turing Award

In 1983, Ritchie and Thompson jointly received the Turing Award for their development of generic operating systems theory and specifically for the implementation of the UNIX operating system. Ritchie's Turing Award lecture was titled "Reflections on Software Research".

IEEE Richard W. Hamming Medal

In 1990, both Ritchie and Thompson received the IEEE Richard W. Hamming Medal from the Institute of Electrical and Electronics Engineers (IEEE), "for the origination of the UNIX operating system and the C programming language".

National Medal of Technology

National Medal of TechnologyOn April 21, 1999, Thompson and Ritchie jointly received the National Medal of Technology of 1998 from President Bill Clinton for co-inventing the UNIX operating system and the C programming language which, according to the citation for the medal, "led to enormous advances in computer hardware, software, and networking systems and stimulated growth of an entire industry, thereby enhancing American leadership in the Information Age".

Japan Prize

In 2011, Ritchie, along with Thompson, was awarded the Japan Prize for Information and Communications for his work in the development of Unix operating system.

 

Thanks Ritchie .Without you, we would not be able to think anything related to computing, O.S., Programming languages, mobile devices etc.

R.I.P. Dennis Ritchie.

Source: http://en.wikipedia.org/wiki/Dennis_Ritchie

use of field pragma in Perl

Perl LogoIt happens many times that you declare a variable name something and calling that variable name by something else. In case of hash in perl, calling that variable or assigning that variable will not give error. It will silently create that key value pair. This is called autovivification.

For ex:  
my $name = "Jassi";
$self->{name} = "Sanjeev aka Jassi"  # it will work as it is
$self->{Name} = "Jaiswal";                    # It will silently create another key value pair.
  # Now if you try to access $self->{name}, it will not give you     
  #Jaiswal. You will get "Sanjeev aka Jassi".

At above example you can see that our motto was to change the value of key “name” but by mistake we wrote “Name”, then also it got updated without any error. So being a human being, we do such typo mistakes and It will be very tough for us to find such bugs.

Before writing a program, lets keep in mind that what variables we are going to use and strict the program to use those variable name only. If I use any other variable than provided one, it should throw error. For this purpose we use “field” pragma.

#!c:/strawberry/perl/bin/perl.exe
{
package Student;

# You may like to give a list of attributes that are only allowed, and have Perl should exit with an error,
#if someone uses an unknown attribute.
# You can do this using the fields pragma i.e use fields fieldname1, fieldname2 etc"
# Isn't it nice feature to secure our code.
use fields 'name',
           'registration',
           'grades';

sub new {
    my($class, $name) = @_;
    $self = fields::new($class);    # returns an empty "strict" object
    $self->{name} = $name;        # attributes get accessed as usual
    return $self;                              # $self is already blessed
 }
}

my $classname = Student->new('Jassi');
$classname->{name} = 'Jassi D\'Costa';  # works
$classname->{Name} = 'foo';  # blows up. If I will not use field pragma, It will silently create this key value pair
                                                      
# for    $classname object.
# End of the program

Here is the screen-shot of the error that you will get.

Minimal things to know about map function in Perl

  Perl is such a nice language that even a beginner can write the fully working code by using simpler things available in Perl.  More you know about Perl  more crazy you will be about it. Its very famous for one liner stuffs and even it has many functions which can minimize our code, run time and our work too!

Map function in Perl is a nice example for it. You can replace you whole foreach code with map in a single line.

  • Perl’s  map functions evaluates expression or a set of block for each element of an array and returns another new array.
  • Each array element is get stored in $_ (local lexical), then it evaluates according to expression or block and pass it to new list of arrays.
  • As hash is nothing but an associative array so you can apply map on that also ex:  %hashVal = map  { lc($_)=>$_  }  @array;   (block example ) or %hashval  = map  + ( lc($_)=>$_ ) ,@array;    (expression example)
  • I just found few different way to write same map function: All will do the same thing , Its just use of regular expression and to differentiate block and expression things.
  • # Method 1 @ucnames = map( ( join " ",  map (ucfirst lc , split)  ) ,@names);
    print "\n########## Printing Values of \@ucnames using map Method 1 ############\n";
    print Dumper(@ucnames);
  • #Method 2 @ucnames = map { join " ",  map {ucfirst lc} split  } @names;
    print "\n########## Printing Values of \@ucnames using map Method 2 ############\n";
    print Dumper(@ucnames);
  • #Method 3 @ucnames = map { join " ", map { s/^(.)(.*)$/uc($1) . lc($2)/e; $_ } split } @names;
    print "\n########## Printing Values of \@ucnames using map Method 3 ############\n";
    print Dumper(@ucnames);
  • Another example :
    Suppose we have an array whose elements are double quoted and we need to remove that. map function could be very useful in this case
     my @out = map { s/"//g; $_ } @arr;

Note: Block does not need comma but expression needs coma explicitly see the examples using { block } and (expression). In simple ,it is

  • map { block } @array or
  • map {expression}, @array or
  • map + { block } , @array (will be treated as expression so comm. Is needed after } )or
  • map (expression , @array)

For fully working code on map function please visit this link For more details on map click here

Minimal Introduction to Perl

 Welcome to Perlistan world! I have been using Perl (Perl 5.10 specifically) from last 1 year and I am really fond of this programming language. There are hell lots of features exist for Perl but I have written only few which I felt is important and interesting for beginners.

Introduction
Perl (Practical Extraction & Report Language) is the Swiss Army knife for  scripting languages(rather call it programming language): powerful and adaptable. It was first developed by Larry Wall, a linguist working as a systems administrator for NASA in the late 1980s, as a way to make report processing easier.

Since then, it has moved into a large number of roles: automating system administration, acting as glue between different computer systems; and, of course, being one of the most popular languages for CGI programming on the Web.

Why did Perl become so popular when the Web came along?
There may be at least two most important  reasons:

First, most of what is being done on the Web happens with text, and is best done with a language that's designed for text processing. More importantly, Perl was appreciably better than the alternatives at the time when people needed something to use. C is complex and can produce security problems (especially with untrusted data), Tcl can be awkward and Python didn't really have a foothold.

Second: It also didn't hurt that Perl is a friendly language. It plays well with your personal programming style. The Perl slogan is “There's more than one way to do it,'' The growth of Internet also complemented Perl. The initial attempt at providing dynamic content was through CGI (even now CGI is used extensively), and Perl's remarkable text handling features made it a quick fit. CGI programming is now synonymous with Perl programming.

CPAN – Comprehensive Perl Archive Network, was set up to share Perl code. Perl supports modules and chances are that for 99% of the programming requirements, there is already a tested module in CPAN (for the remaining 1%, write modules and contribute to CPAN!). Using modules really mask the complexities of adhering to pre-defined standards and frees you to concentrate on your tasks – no point in re-inventing the wheel. Now, you have modules which handles graphics, CGI etc… You can also embed Perl code in your C/C++ programs. A very popular embedded Perl architecture is mod_perl for Apache web server.

Lets dive little bit deeper

Data manipulation
Perl can handle strings, dates, binary data, database connectivity, streams, sockets and many more. This ability to manipulate multiple data types help immensely in data conversion (and by the way, it is much faster than PL/SQL!). Perl also has provision for lists (or arrays) and for hashes (associative arrays). Perl also supports references, which are similar to the pointers in C. Lists, hashes and references together make it possible to define and manipulate powerful custom-defined data-types.

Portability Most of the Perl code will run without any change in Unix or Windows or Macintosh. Typical changes you might have to make include specifying file paths and use of low-level OS specific functions.

CGI CGI.pm. Period. Almost all CGI programs written today are using the CGI.pm module from CPAN. Even before this was written, people used to use Perl extensively for CGI programming. CGI.pm made the process streamlined and easy, even for beginners. The graphics library GD is used extensively in producing dynamic web charts. Ever since Kernighan and Ritchie came out with C programming language, people have started learning almost any programming language with the obligatory "Hello World" program. Let us do the same!

Hello World!

Here is the basic perl program that we'll use to get started.

[perl] #! /usr/bin/perl
# prints Hello world.
use strict;
use warnings;
print 'Hello world.';                # Print a message [/perl]

#!  is called sh-bang (she bang 😉 ). Always let it be your first line of code in your program.  Write the location of executable perl here. Always try to write use strict and use warnings in your program. It will minimize error and you will be following standard coding rules !

Comments Perl treats any thing from a hash # to the end of line as a comment. Block comments are not possible. So, if you want to have a block of comments, you must ensure that each line starts with #.

Statements Everything other than comments are Perl statements, which must end with a semicolon, like the last line above. Unlike C, you need not put a wrapping character \ for long statements. A Perl statement always ends with a semicolon.

Running Perl Write a small  program using a text editor, and save it. The first line of the program is a typical shell construct, which will make the shell start the interpreter and feed the remaining lines of the file as an input to the interpreter. After you've entered and saved the program make sure the file is executable by using the command

[perl]
chmod u+x perlfile
[/perl]

at the UNIX prompt, where perlfile  is the filename of the program (of course with .pl or .pm extension mostly). Now, to run the program, just type any of the following at the prompt.

[perl]
perl perlfile
[/perl]

If something goes wrong then you may get error messages, or you may get nothing. You can always run the program with warnings using the command

[perl]
perl -w progname
[/perl]

at the prompt. This will display warnings and other (hopefully) helpful messages before it tries to execute the program. To run the program with a debugger use the command

[perl]
perl -d progname
[/perl]

When the file is executed Perl first compiles it and then executes that compiled version. Unlike many other interpreted languages, Perl scripts are compiled first, helping you to catch most of errors before program actually starts executing. In this context, the -w switch is very helpful. It will warn you about unused variables, suspicious statements etc.