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);

How chomp and chop function works in Perl

How chomp and chop function works in PerlWhat is chomp and chop?
chomp()
The chomp() function will remove (usually) any new line character from the end of a string. The reason we say usually is that it actually removes any character that matches the current value of $/ (the input record separator), and $/ defaults to a new line. It returns the total number of characters removed from all its arguments and If VARIABLE is omitted, it chomps $_

So, if $/ =”\t” then chomp would remove every tab instead of new line.
 
For more information on the $/ variable, try perldoc perlvar and see the entry for $/ and perldoc -f chomp
Note: if chomp doesn’t behave as it should by default, hint is to check record separator ($/)

chop()
Sometimes you will find you want to unconditionally remove the last character from a string. While you can easily do this with regular expressions, chop is more efficient. Check perldoc -f chop
 
The chop() function will remove the last character of a string (or group of strings) regardless of what that character is and return the last character chopped. In case of array it return the last character chopped of the last element of the array. Note, if you want to easily remove newlines or line separators see the chomp().

As chop return the last character chopped of the string , if you want it's reverse i.e. return all characters except the last from the string you could use substr($string, 0, -1)
 
Chomp and chop, both functions can be applied on strings,array,hash. We would see it by three examples for each functions.
 
Example 1. Chomping a string
Most often you will use chomp() when reading data from a file or from a user. When reading user input from the standard input stream (STDIN) for instance, you get a newline character with each line of data. chomp() is really useful in this case because you do not need to write a regular expression and you do not need to worry about it removing needed characters.
When running the example below, using the enter key on a line by itself will exit the program.
 
[perl]#!/usr/bin/perl
  use strict;
  use warnings;
  my $username = <STDIN>;
  print "before chomp: $username";
  chomp $username; #or chomp($username); or chomp (my $username =<STDIN>); in one line
  print "After chomp: $username";[/perl] 
Output:
[vim][Sanjeev@Alien Coders]$ perl chomp_examples.pl
Alien Coders
before chomp: Alien Coders
After chomp: Alien Coders[Sanjeev@Alien Coders]$[/vim] 

First print got printed with new line which you entered while typing. Yes, it took new line (pressed enter) also as user input. Second line removed that new line, so second print is displayed along with shell on the same line.
 
Example 2. Chomping an array
If you chomp an array, it will remove  newline from the end of every element in the array:
 [perl] #!/usr/bin/perl
  use strict;
  use warnings;
  my @array = ("sanjeev\n", "Jassi", "AlienCoders\n");
  print "Before chomp:\n";
  print "@array\n";
  chomp(@array);
  print "After chomp:\n";
  print "@array\n";[/perl]
Output:
[vim]Before chomp:
sanjeev
 Jassi AlienCoders
 
After chomp:
sanjeev Jassi AlienCoders[/vim]
As you can see, the newlines have been removed from "sanjeev" and "AlienCoders", but no characters have been removed from "jassi".
 
Example 3. Chomping a hash
If you pass a hash into chomp() function, it will remove newlines from every value (not key) of the hash. Remember key is always unique and string (internally). So, if you add new line in key then use that new line char also while using that key. Better to avoid such nasty thing:
 
 [perl] #!/usr/bin/perl
  use strict;
  use warnings;
  use Data::Dumper;
 
my %hash = (
    'first' => "one\n",
    'second' => "two\n",
    'third' => "three\n",
  );
  print "before chomp:\n";
  print Dumper(\%hash);
  chomp(%hash);
  print "after chomp:\n";
  print Dumper(\%hash);[/perl]
Output:
[vim]before chomp:
$VAR1 = {
          'first' => 'one
',
          'second' => 'two
',
          'third' => 'three
'
        };
after chomp:
$VAR1 = {
          'first' => 'one',
          'second' => 'two',
          'third' => 'three'
        };[/vim]
It clearly shows that how new line is effective before chomp and it looks nice after chomp.
 
Example 4. Chopping a string
The chop() function removes and returns the last character from the given string whatever it is. So don’t do any mistake by assuming that it removed new line from the user input with its first use. When you will use it second time it will again remove one more character from user input but chomp only and only removes new line (or whatever is stored in $/).
 
  [perl]#!/usr/bin/perl
  use strict;
  use warnings;
 
  my $string = 'Perl';
  my $char = chop($string); #to return the chopped character in a variable
 
  print "String: $string\n";
  print "Char: $char\n";[/perl]
 
Output:
 [vim]String: Per
Char: l[/vim] 
 
Example 5. Chopping an array
If you pass the chop() function to an array, it will remove the last character from every element in the array.
 
  [perl]#!/usr/bin/perl
  use strict;
  use warnings;
 
  my @arr = ('Jassi', 'Sanjeev', 'Alien Coders');
  my $last_char = chop(@arr);
 
  print "@arr\n";
  print "Last Char: $last_char\n"; #it will store last character of last element in the array[/perl]
Output:
[vim]Jass Sanjee Alien Coder
Last Char: s[/vim] 

Example 6. Chopping  a hash
If you pass a hash into chop() function , it will remove the last character from the values (not the keys) in the hash. For example:
 
 [perl] #!/usr/bin/perl
  use strict;
  use warnings;
  use Data::Dumper;
 
  my %hash = (
    first => 'one',
    second => 'two',
    third => 'three',
  );
 
  print “Before chop:\n”;
  print Dumper \%hash;
 
  my $chr = chop(%hash);
  print “After chop: \n”;
  print Dumper(\%hash); 
 
  print "Char: $chr\n"; #it always have last character of last value in hash[/perl]
Output:
[vim]Before chop:
$VAR1 = {
          'first' => 'one',
          'second' => 'two',
          'third' => 'three'
        };
After chop:
$VAR1 = {
          'first' => 'on',
          'second' => 'tw',
          'third' => 'thre'
        };
Char: e[/vim]

Note:

  • chop and chomp functions would not work on array/hash reference or array of array/hash reference. So, avoid using this on referential things.
  • Always use parenthesis, if you are using assignment operator while chomping or chopping.
    chomp $value = <STDIN>;  doesn't work  but chomp($value=<STDIN>); works

Credit: http://perlmeme.org

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]

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.

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
  
 

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.