Monday, August 8, 2011

Perl Program of the Day August 8th

See this Place everyday to learn a perl program with explanation line by line

Today we will learn how to remember a Pattern while substitution.

I will try to explain this concept using a simple program.

Consider i have a line with content "My name is RAMU".Here i want to remember the last word in the line.i.e name of the person and Ask him a question in the format
(Name of the person) ,How are you?

2)$line="My name is RAMU";
3)$line =~ s/.*?\b(\w*)$/\1,How are you?/;
4)print $line."\n";

Ramu,How are you?

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:This is the line where the main logic happens.
s/.*?\b(\w*)$/\1,How are you?/;
s  - signifies substitution
".*" -  matches the pattern "My name is " and ? is to make the match non-greedy
\b - to specify to start a word-boundary .i.e the name Ramu in this case
\w - typically matches a character in perl since i have specified \w*$ it matches the entire word till the end of the word.
Here the remembrance takes place by the brackets "(  )" any thing inside the brackets are remembered.And the remembered word is stored in \1 in this case.If you made it to remember two patterns the pattern would have been matched into \ 1 and \2 respectively.And this goes on .One  important thing is the brackets should not be backslashed if so the pattern will not be remembered and it will be considered as normal brackets.
/\1,How are you/
As explained above \1 gets replaced by Ramu in this case and Ramu,How are you gets saved in the $line.
4th line:It is simply for the $line scalar to get printed.

If you want to get a basic idea of substitution in Perl refer to yesterday's Program of the day:
Perl program of the day 7th august