Sunday, August 7, 2011

Perl Program of the Day August 7th 2010

See this Place http://linux-forum-karthik.blogspot.com/ everyday to learn a perl program with explanation line by line

Today we will learn to write a simple program to substitute a word with another word in Perl

Here i am trying to sustitute the word "hello" with "Hai" in a line.

1)#!/usr/bin/perl
2)$line="hello great wonderful awesome";
3)$line =~ s/hello/hai/;
4)print $line;

Explanation:
1st line:First line starting with "#!" is important as it says the path of the interpreter it depends on the way the perl was installed on your computer.It is very necesary if you don't end the file name with ".pl"
2nd line:$line is a scalar as it starts with "$".So i am trying to store the line in the
scalar.
3nd line:Here is the main part of the program.
when you want to substitute anything in a scalar.You have to specify that scalar to the left side.Here i want to substitute in the scalar $line so i have specified it to the left.
Next part is "=~" which has to be used when you match or substitute in Perl.
s/hello/hai/
Here "s" specifies substitution
And the word to be replaced has to be given first followed by word to be replaced separated by "/".
By this line the word hello gets replaced by hai.
4nd line:It is just simply to print the line.

Hope this gives a glance of one of the powerful abilities of Perl.

No comments:

Post a Comment