Wednesday, November 16, 2011

Replacing Values in text File

#!/usr/bin/perl -w

# Print the value of the command line arguments
#$numArgs = $#ARGV + 1;
#print "You provided $numArgs arguments\n";
print "Input file is $ARGV[0]\n";
print "Output file is $ARGV[1]\n\n";

# Open input file in read mode
open INPUTFILE, "<", $ARGV[0] or die $!;
# Open output file in write mode
open OUTPUTFILE, ">", $ARGV[1] or die $!;

# Read the input file line by line
while (<INPUTFILE>) {

  $_ =~ s/Fusion.test/sriram.test/g;
  $_ =~ s/weblogin.test/newnewlogin.test/g;
  print OUTPUTFILE $_;
}


close INPUTFILE;
close OUTPUTFILE;

====================================

sriram@ubuntu:~/perl$ ./check.pl value.txt output.txt
Input file is value.txt
Output file is output.txt

sriram@ubuntu:~/perl$

Reading a argument in perl

$ cat argv.pl
#!/usr/bin/perl
print 'First Argument: ' . $ARGV[0];
print "\n********************\n";
print 'Second Argument: ' . $ARGV[1] ;
print "\n********************\n";
print 'Third Argument: ' . $ARGV[2];


sriram@ubuntu:~/perl$ ./argv.pl  1 2 333First Argument: 1
********************
Second Argument: 2
********************
Third Argument: 333

Sunday, November 13, 2011

How To Configure Perl with Httpd/Apache in Fedora.

Install httpd and mod_perl using yum

check perl module is available in /etc/httpd/modules/mod_perl.so

Load Module :

in /etc/httpd/conf/httpd.conf

LoadModule perl_module modules/mod_perl.so

Add this line , which will enable you to run perl :


ScriptAlias /perl /var/www/perl/
<Location /perl/>
   allow from all
   SetHandler perl-script
   PerlHandler ModPerl::Registry
   PerlResponseHandler ModPerl::PerlRun
   AddHandler cgi-script .cgi .pl
   #PerlHandler ModPerl::PerlRun
   Options FollowSymLinks +ExecCGI
  PerlSendHeader On
</Location>


Permissions of directories:
#cd /var/www/
# ls -la
total 28
drwxr-xr-x.  7 root root 4096 Nov 13 19:55 .
drwxr-xr-x. 23 root root 4096 Nov  5 15:11 ..
drwxr-xr-x.  2 root root 4096 Oct 27  2010 cgi-bin
drwxr-xr-x.  3 root root 4096 Nov 13 18:53 error
drwxr-xr-x.  3 root root 4096 Oct 27  2010 html
drwxr-xr-x.  3 root root 4096 Nov 13 18:53 icons
drwxr-xr-x.  2 root root 4096 Nov 13 20:08 perl

# cd /var/www/perl

# ls -la
total 12
drwxr-xr-x. 2 root   root   4096 Nov 13 20:08 .
drwxr-xr-x. 7 root   root   4096 Nov 13 19:55 ..
-rwxr-xr-x. 1 apache apache   77 Nov 13 20:08 test.pl
#


Tuesday, November 8, 2011

Writing to File using Perl

sriram@ubuntu:~/perl$ cat file1.txt (File toWrite to)
The Rock|Cheer|Rock Bottom
Triple H|Boo|Pedigree
Stone Cold|Cheer|Stone Cold Stunner
sriram@ubuntu:~/perl$

sriram@ubuntu:~/perl$ cat write.pl(Perl Script to Write)
#!/usr/bin/perl
open (TEST, '>>file1.txt')
print TEST "Sriram Test \n";
close(TEST);

Result :

sriram@ubuntu:~/perl$ cat file1.txt (Result)
The Rock|Cheer|Rock Bottom
Triple H|Boo|Pedigree
Stone Cold|Cheer|Stone Cold Stunner
Sriram Test
sriram@ubuntu:~/perl$









Reading from a File in Perl


sriram@ubuntu:~/perl$ cat file1.txt
The Rock|Cheer|Rock Bottom
Triple H|Boo|Pedigree
Stone Cold|Cheer|Stone Cold Stunner

sriram@ubuntu:~/perl$ cat read.pl
#!/usr/bin/perl
 open (MYFILE, 'file1.txt');
 while (<MYFILE>) {
        # To clear the new line use chomp
        chomp;
        print "$_\n";
 }
 close (MYFILE);


output:
sriram@ubuntu:~/perl$ ./read.pl
The Rock|Cheer|Rock Bottom
Triple H|Boo|Pedigree
Stone Cold|Cheer|Stone Cold Stunner


Few explanations :

Inside the loop, we use the chomp function to clear off the newlines from the end of each line, then we print the value of $_ to show that it was read.
  chomp;
  print "$_\n"; 

MYFILE is File Handle created you can use anything.



For more info, check this :

http://perl.about.com/od/perltutorials/a/readwritefiles.htm


Friday, November 4, 2011

Function - Substring (substr)

 Substring (substr)
The substring function is a way to get a portion of a string value, rather than using the entire value.
The value can then be used in a loop or a conditional statement, or just for its own purposes.
For this one, you will probably want the general form of the function first.
The function is usually set to a variable so that the variable contains the value of the substring:


$ cat substr.pl
#!/usr/bin/perl
use strict;
my $test="sriram";
my $new = substr($test,3,5);
print "the new value of substring is $new\n";

sriram@ubuntu:~/perl$ ./substr.pl
the new value of substring is ram
sriram@ubuntu:~/perl$

Length Function in Perl

Length Function :

Length:
The length function simply gives you back the number of characters in a string variable.

This is handy when you don't know the value of the variable but would like to know the number of characters it has.
It is useful with arrays, conditional statements, loops, and such things.

$ cat length.pl
#!/usr/bin/perl
use strict;
my $test="sriram";
#my $len = length ($test);
my $ti = length($test);
print "The lengh of variable is $ti \n";


$ ./length.pl
The lengh of variable is 6
$

Chop Function

Chop function :

The chop function is used to "chop off" the last character of a string variable

# cat chop.pl
#!/usr/bin/perl
use strict;
my $sriram = "Sriram";
chop($sriram);
print "$sriram \n";

Result :
# ./chop.pl
Srira
#

HTML in Perl

bash$cat html.pl
#!/usr/bin/perl
#use CGI::Carp qw(fatalsToBrowser);
print "Content-type:text/html\n\n";
print <<'EndHTML';
<html>
<head>
<title>Fish Report</title>
</head>
<body>HTML Test message </body>
</html>
EndHTML


This print command tells the program to print the HTML code until it finds the word EndHTML again on its own. You can use any word or group of letters you like, just be sure you use the same thing when you want to end the HTML code. For instance, some people use EOM to do this.

print <<EOM;
....your HTML code here.....

EOM 


 To check if HTML syntax are ok :

# perl -c html4.pl
html.pl syntax OK











Thursday, November 3, 2011

Unshift/Shift

Unshift/Shift :
===========

If you want to simply add or delete an element from the left side of an array (element zero),
you can use the unshift and shift functions.

Unshift (To add a element in element zero) :
===========================


#!/usr/bin/perl
@test = ("test2","test3");
unshift(@test,"test1-added");
print "Added new element using unshift\n @test\n";


$ ./unshift.pl
Added new element using unshift
 test1-added test2 test3
$

Shift (To delete the zero element in an array):
=============================

#!/usr/bin/perl

@sriram = ("one","two","three","four");
shift(@sriram);

print "New Value is \n @sriram\n";

Replace Values in Array using Splice:

$ cat replace_array.pl
#!/usr/bin/perl
@numbers=("one","two","three","four");
splice(@numbers,1,2,value2,value3);
print "The replace values are \n @numbers\n";


$ ./replace_array.pl
The replace values are
 one value2 value3 four
$

Explanation :

defined array name as numbers :
@numbers=("one","two","three","four");
 
 This will replace values inside numbers[1] and numbers[2]
 with value2 and value3.

 splice(@numbers,1,2,value2,value3);














To delete an element in Array using splice

Splice functions are used to delete / add / replace elements in an existing array:

Below example we see how to  delete elements in array

$ cat splice.pl
#!/usr/bin/perl
@numbers =("one","two","three","four","five","six","seven","eight");
splice(numbers,1,2);
print "array values in Numbers are :\n @numbers\n";
$


You'll see three arguments inside the splice(numbers,1,2); of the splice function above.
The first one is just the name of the array you want to splice.
The second is the list number of the element where you wish to start the splice (starts counting at zero).
The third is the number of elements you wish to splice.

In this case, we just want to splice two elements.
 The code above deletes the element at list number 1 and 2, which is "two","three"

So result should be below

$ ./splice.pl
array values in Numbers are :
 one four five six seven eight
$

To access an element in an Array

#!/usr/bin/perl
@test=("a","b","c");
print "3rd element is \n @test[2]\n";

Please note array starts with zero,one,two ....
so when we say 2 the element is c on the above example.

Wednesday, November 2, 2011

Perl Basics 1



1) To find all installed modules for your perl in your host :

root@ubuntu:~# perl -MCPAN -e 'CPAN::Shell->r'
---------------------------------------------------------------
List::Util                     1.21      1.23  GBARR/Scalar-List-Utils-1.23.tar.gz
Locale::Constants              2.07      3.16  SBECK/Locale-Codes-3.16.tar.gz
Locale::Country                2.07      3.18  SBECK/Locale-Codes-3.18.tar.gz
Mail::Address                  2.06      2.08  MARKOV/MailTools-2.08.tar.gz
PerlIO::scalar                 0.07      0.12  RJBS/perl-5.15.2.tar.bz2
Pod::Man                       2.22      2.25  RRA/podlators-2.4.0.tar.gz
Socket                         1.82      1.94  FLORA/perl-5.13.11.tar.gz
mod_perl2                  2.000004  2.000005  PHRED/mod_perl-2.0.5.tar.gz
233 installed modules have no parsable version number
(use 'o conf show_unparsable_versions 1' to show them)
-------------------------------------------------------------------------

Installing Perl Modules :

root@ubuntu:~# perl -MCPAN -e shell
Terminal does not support AddHistory.

cpan shell -- CPAN exploration and modules installation (v1.9402)
Enter 'h' for help.

cpan[1]> install File::Compare
CPAN: Storable loaded ok (v2.20)
Going to read '/root/.cpan/Metadata'
  Database was generated on Wed, 09 Nov 2011 04:30:34 GMT
File::Compare is up to date (1.1006).





2) Use of perl module strict :
use strict;
'use strict' turns on the 'strict' pragma which will make you declare your variables with the my keyword.

3) Use of my in variables?
Variables that you use in a subroutine should be made private to that subroutine with the my operator.
This avoids accidentally overwriting similarly-named variables in the main program.
If you already included use strict at the top of your program, perl will check that all variables are introduced with my.

4) Variable Declaration

my $scalar;  # $scalar is private
my @array;   # now @array is private
my %hash;    # %hash is private

5) Loops in Perl


A) For Loop :
=============

for (starting assignment; test condition; increment)
{
 code to repeat
}

Well, that's great, but it doesn't tell us much about what happens. Instead, let's use a real example. Let's say we wanted to print the word "cool" ten times in a row. We could use a for loop like this:

#!/usr/bin/perl
for ($count=1; $count<11; $count++)
{
 print "cool\n";
}




B) While Loop :
================

Unlike the for loop, the while loop does not have a self-contained way to alter the initial expression.



#!/usr/bin/perl
$i=1;                  /* initial expression set to 1 */
while ($i < 10) {     /* Next comes the start of the while loop, and the expression in the parenthesis is evaluated: */
print "$i\n";         /* Execute the code block inside the while loop.  */
$i++;                  /* Execute the increment value inside codeblock */
}





C) Foreach loop:
=================

The foreach loop is one that is often used with some sort of array.

foreach variable_name (array_name)
{
 code to repeat
}

#!/usr/bin/perl
@names=("a","b",'c","d");
print "Print Names in array \n";

foreach $i (@names)
{
print "$i\n";
}