Various ways to print the content of hash in Perl

What is the various ways to print the contents of a hash?

Hash in Perl is nothing but an associative array i.e. Each key is associate with its value and can be displayed using either key or value. It is preferred over simpler array because instead of printing value based on index number, you can print by using key.
Ex:
[perl]$hash{'key'} = 'value';
[/perl]
We will discuss Hash fundamentals in another tutorial where I will explain everything which is required to understand hash clearly with some examples. Let’s see here, how we can display the contents of hash. We assume we have a hash defined as %hash = (some key value pairs);

Read more

Delete Function in Perl with examples

“delete” function in Perl is mainly used to delete the given element/key, which in return deletes its associated value(s) too. So, exists() on such key would return false.
Note: Assigning undefined value to a key in has doesn’t remove its key but delete() function would do that. So, use delete() or assigning undefined value wisely.
The general syntax for delete function is:
[perl]delete EXPR
[/perl]

Read more

How to make online songs repository using Perl

Problem Scenario:
Write a Perl script which will search all sub directories and its files under a given sub-directory and would do the following:

  1. Display all directories on a web page
  2. When user clicks on any of the list directories show files under it (toggle things)
  3. When user clicks on file, it should play that song using yahoo media player
  4. You should use CSS3, JavaScript and Perl only
Read more

How to use Perl to fetch website details

Whenever I was surfing any good technical website,  I was getting curious to know what’s its page rank, alexa rank, where it is hosted, who handles its mails, when this domain was registered and by whom, when it will get expired and so on.
For all these, I had to visit different websites to gather all such information, then I thought it’s better to write a script which will fetch all the details for me and came up with site info details script using Perl.
Fully working code is available here.

Read more

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.

Read more

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

Read more