IP Address To decimal and vice-versa using Perl

There can be a situation where we need to convert IPv4 Address(32 bit) from 4 octet format i.e. 127.0.0.1 to  it decimal equivalent value i.e.  2130706433 and vice-versa. We can use pack, unpack in-built Perl functions to achieve this situation or we can use Socket.pm module (if allowed) along with pack and unpack, whichever you feel easier; you can use it in your code.

Methods to Install Perl modules from CPAN

Installing Perl modules from CPANIf you are working on Perl and you need to work on modules which is listed in CPAN. You may need to download it, install it and use it in your box.

For that you need to know how to install Perl modules. This article will show you simple steps to download and install Perl modules in Linux box. I know it’s not the new topic for Perl chapter but I wrote it for our standalone repository on Perl and moreover, all these method with examples and pitfalls are not listed at many places. So, I think it will be worthy for our viewers and Perl mongers 😀

Method 1 using cpan shell(It has advantage over manual installation. Read Note section at the bottom)

1. perl -MCPAN -e shell
cpan> install HTML::Template
or
2. perl -MCPAN -e ‘install HTML::Template’
or
3. cpan -i  MIME::Lite

Method 2 Manual module installation
if you’re having problems installing with CPAN. If you’re on the command line, you can use something like wget to grab the file. Next you’ll want to unzip it with something like:

tar -zxvf HTML-Template-2.8.tar.gz

In case above command doesn’t work for you, try this
gzip -d XML-Parser-2.36.tar.gz
tar -xvf XML-Parser-2.36.tar

This will unzip the module into a directory, then you can move in and poke around – look for the README or INSTALL files.

In most cases, installing a module by hand is still pretty easy, though (although not as easy as CPAN). Once you’ve switched into the base directory for the module, you should be able to get it installed by typing:(I assume you are on Linux box)
1. perl Makefile.PL
2. make
3. make test
4. make install

If everything shows fine then That’s it. You are now ready to rock and roll with newly installed Perl modues 😀
 

But what if cpan command doesn’t work for method 1?
1. Check first if cpan command works in your box
$cpan
cpan: Command not found.
If you get the above result means you need to install cpan module to work from CPAN otherwise, you have cpan installed in your system and you can skim next steps 😀

2. yum install perl-CPAN

3. after successful download and installation. Type cpan for the first time use
and type o conf commit on cpan prompt
then type quit on cpan prompt

You are done!  Now Method 1 will work without fail.

 

Note: If any CPAN module is dependent on the several other modules. CPAN automatically resolves the dependencies and installs other dependent modules. 

cpanm module is more advanced for doing all these without hassle. If possible give it a try.

[ADDED LATER]
As it was commented through Facebook by one of our readers, so I thought to better update this article with his comments.

# Install cpanminus (once).
curl -L http://cpanmin.us | perl – –self-upgrade or
cpan App::cpanminus
# Install your CPAN modules.
cpanm HTML::Template
cpanm XML::Parser
 

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.

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.