Tuesday, August 9, 2011

Perl Program of the day August 10th 2010


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


Today we see how to substitute a word in the entire file.

Content of List.txt before execution:
Hi gopal,how are you
Hi james,how are you
Hi,how are you
Hi Thomas,how are you
Hi Manjula,how are you
Hi karthik,how are you

Content of the Perl file:

1)#!/usr/bin/perl
2)use File::Copy;
3)open(FH," ;
5)close(FH);
#For creating the temp file and adding the line no
6)$dd=grep(s/Hi/Hai/,@ddd);
7)open(FH1,">list.txt.bak");
8)foreach(@ddd)
9){
10)print FH1;
11)}
12)close(FH1);
13)move("list.txt.bak","list.txt") or die "cannot move";
14)# for moving the temp file to the original files
15)unlink("list.txt.bak") or die "cannot delete the file";
16)# for removing the temp file

Content of List.txt after execution:
Hai gopal,how are you
Hai james,how are you
Hai,how are you
Hai Thomas,how are you
Hai Manjula,how are you
Hai karthik,how are you


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: use File::Copy is a default module used in Perl so as to use functions Perl functions move and unlink later.
3nd line:opens the file list.txt for reading indicated by the option "<" .FH is the file handler. 4nd line:Entire content of the file list.txt signified by is copied to array @ddd each element in the array @ddd is a line in the file separated by "\n";
5nd line:closing the file handler.
6nd line:This is a important line which does the substitution.
$dd=grep(s/Hi/Hai/,@ddd);for more details regarding grep refer to the Perl article "grep in Perl" with the url http://linux-forum-karthik.blogspot.com/2011/07/grep-in-perl.html
Here grep substitutes Hi with Hai for the entire iteration of the array @ddd.And the no of substitution are saved in the scalar $dd.And the array @ddd is changed now.
7nd line:Here i am basically trying to create a temp file list.txt.bak for writing signified with ">" and the write the content of the array @ddd to it by the line "print FH1".TO understand better refer to the File examples to the right.
13nd line:I am trying to use the move function to move file "list.txt.bak" to "list.txt".
15nd line : i am trying to remove the temp file "list.txt.bak"

No comments:

Post a Comment