Sunday, July 31, 2011

Extensions in perl

Extensions significantly add to the power of regular expressions instead of adding lot of metacharacters.

Commonly used extensions in perl are:
1)(?#TEXT)    - it is used for adding comments in the regular expressions.

2)(?:...)       - it is used in case when you want paranthesis to be used without saving
the matched pattern in $n

3)(?=...)    -  it is used for matching without using the specific value in the $& variable.

4)(?!...)  - it is used when you don't want the pattern in the paranthesis to follow the word before or after.

Example:
1)(?#TEXT)-
it can be used simply used it just adds a clarity to the people viewing this pattern.
$dd =~ m/\w(?#it matches a single character)\s(it matches a single character)/;

2)(?:.....)-


$dd="hello how are you";
$dd=~ m/(?:\w*)/;
print $1;

if you see the example above the $1 is supposed to match hello since "?:" is specified in parantheses it is empty.

3)(?=...)-
it can be used in the case when you want to match a pattern based on the value in the paranthesis but it should not get included in $& variable in that case this will be useful.

$dd="hello how are you";
$dd=~ m/\w*\s+(?=how)/;
print $&;

Output:
hello

In the example specified i am trying to match a word followed by "how".If i have
parathesis without "?=" the output will be "hello how".Using "?=" has done the trick to print only hello.

4)(?!....)
It is very useful extension which can be used in case where you donot want a word to follow or precede the match you are looking for.
For example: m/red(?!carpet)/ will match redsea or redfly but not redcarpet.
The detailed example can be seen in the url:
http://linux-forum-karthik.blogspot.com/2011/07/to-match-pattern-not-having-word.html



Saturday, July 30, 2011

map vs grep in perl


grep function in perl:
grep function is normally used to select the matched pattern and return it to the array

grep(EXPRESSION,@array);
grep(BLOCK,@array);

Perl file:

$"="\n";
$\="\n";
@array=(0..3,"karthik");
print "@array";
@result=grep($_=~ s/0/9/,@array);
print "array:\n@array";
print "result:\n@result";

output:

G:\perl_programs>perl perl_map.pl
0
1
2
3
karthik
array:
9
1
2
3
karthik
result:
9

G:\perl_programs>

Analysis:
In this case if you see the grep function tries to substitute 0 with 9 by moving through each element of the array.When it finds a element with value 0 it
modifies the original array and returns the replaced value to the result array.
So as you may see from the output the result array has only one value "9".

Map function in perl:
Map function is used to evaluate the given expression and return t
he result value to the array.


$"="\n";
$\="\n";
@array=(0..3,"karthik");
print "@array";
@result=map($_=~ s/0/9/,@array);
print "array:\n@array";
print "result:\n@result";


Output:

G:\perl_programs>perl perl_map.pl
0
1
2
3
karthik
array:
9
1
2
3
karthik
result:
1






G:\perl_programs>

Analysis:
In this case if you see the map function tries to substitute 0 with 9 by moving through each element of the array similar as in grep.But When it does not 
find the match it returns empty string to the result array and when it finds the match it modifies the original array with the substituted value and returns the "1" to the result array which is the return value for pass or fail for the substitution.
So as you may see from the output the result array has only one value "1" followed
by space for the values which did not match.

finding the count of a certain character in a line perl


Perl Program:

$_="great,awesome.wonderful  wonder";
$dd=tr/w//;
print "count of character w is :$dd";

Output:

G:\perl_programs>perl perl_tr.pl
count of character w is :3

G:\perl_programs>
Analysis:
Here i have used tr operator to find the count of character 'w'.tr operator is normally used to translate the characters.But in this case i have translatted 'w' into
nothing as per the pattern "tr/w//".So it just returns the no of character matched in the line.

Friday, July 29, 2011

finding the no of values in array match a pattern

grep can also be used to find no of values in a array match the pattern specified by assigning to the scalar.
using the below example:


@a=('one','Two','Three','Four','Five');
$ff=grep(/^T/,@a);
print "$ff";

Output:

G:\perl_programs>perl perl_grep.pl
2
G:\perl_programs>

Explanation:
Here the pattern searched through arrays is "^T".So here Two and Three values match Since it is assigned to a scalar it is converted to 2(no of values that match)

grep in perl


1)grep in perl can be used to search a pattern in a array and print the values that match to a array.


@a=('one','Two','Three','Four','Five');
@ff=grep(/^T/,@a);
print "@ff";


G:\perl_programs>perl perl_grep.pl
Two Three
G:\perl_programs>

Explanation:
Here the pattern searched through arrays is "^T".So here Two and Three values match and it is assigned to the array.

2)grep can also be used to find no of values in a array match the pattern specified by assigning to the scalar.
using the below example:

@a=('one','Two','Three','Four','Five');
$ff=grep(/^T/,@a);
print "$ff";

Output:

G:\perl_programs>perl perl_grep.pl
2
G:\perl_programs>

Explanation:
Here the pattern searched through arrays is "^T".So here Two and Three values match Since it is assigned to a scalar it is converted to 2(no of values that match).

3)It can also be used to process the arrays such as substitute ceratin content of array likewise


@a=('one','Two','Three','Four','Five');
$ff=grep(s/Two/zero/,@a);
print "The no of values where it was substituted:$ff"."\n";
print "The changed array:@a"."\n";

Output:

G:\perl_programs>perl perl_grep.pl
The no of values where it was substituted:1
The changed array:one zero Three Four Five

G:\perl_programs>

Explanation:
Here the grep function is used to substitute Two with zero by moving through every array content.

4)grep function can also be used to print the array content .But it is not preferred it is better to use map function for that:

@a=('one','Two','Three','Four','Five');
$ff=grep(print("$_\n"),@a);


Output:


G:\perl_programs>perl perl_grep.pl
one
Two
Three
Four
Five
G:\perl_programs>

Monday, July 25, 2011

perl array newline



#!/usr/bin/perl
$"="\n";
@array1=("hello","great","awesome","wonderful");
print "@array1";

Here the special variable $" is used which is the separator used between the list elements when an array variable is interpolated into double quotes.Normally this value is set to default as space.Here i have made this value expilictly as "\n" to make it print in a newline.

Output:

G:\perl_programs>perl perl_array_print.pl
hello
great
awesome
wonderful
G:\perl_programs>perl perl_array_print.pl


print with newline perl



$\="\n";
print "@hell";
print "marvellous";
print "great";
print "asasasasas"."ffffff"."fdifdfd";
print "awesome";

Here the special variable "$\" is used which is added as  the invisible element to end of the print statement .Normally it is empty it can be assigned "\n" if you want to print everytime in a newline.

output:

G:\perl_programs>perl perl_print.pl

marvellous
great
asasasasasfffffffdfdfd
awesome

G:\perl_programs>




Sunday, July 24, 2011

To join all the content of the file into a scalar perl


Content of the list.txt:

hello gopal,how are you,
hello james,how are you
hello,how are you,
hello Thomas,how are you,
hello Manjula,how are you,
hello karthik,how are you

Content of the Perl file:

$ddd=getfile("list.txt");
print $ddd;
 sub getfile {
          my $filename = shift;
          local *F;
          open F, "< $filename" or die "Couldn't open `$filename': $!";
          local $/ = undef;           # Read entire file at once
          $contents = <F>;            # Return file as one single `line'
          close F;
          return $contents;
        }

output:


G:\perl_programs>perl perl_filehandle.pl
hello gopal,how are you,
hello james,how are you
hello,how are you,
hello Thomas,how are you,
hello Manjula,how are you,
hello karthik,how are you
G:\perl_programs>

Analysis:
Here the entire content of the file is joined into a scalar by changing the input record separator("$/")  to be undef which is by default to "\n".By using the local scope to the record separator the change is visible only in the subroutine getfile.

Scope in Perl

Scope avaible in perl:
1)my
2)local
3)our

my scope:
1)By this scope we mean that variables defined with my are accessible only within the block
and it is not even accessible for the functions called from the block.
2)here it creates a lexical scope for the variable(only accessible within the block)
3)it is more preferrable than the other scope as it does not overwrite the value .
4)it makes a variable private in lexical scope.

local scope:
1)Here the temp variable is created in the dynamic scope.
2)The dynamic scope it means the variable not only visible within the block but it is also visible in the function called from the block.
3)it is mainly used in cases where using "my" may prove illegal especially for special variables.
4)it makes variable private in a dynamic scope.

our scope:
1)It is definitely not private and it is the default thing which is used when you don't specify any scope;
2)it is global
3)Even outside the package it can be accessed by using Packagename::variablename;


Example:
Content of Perl file:


firstSub("AAAAA", "BBBBB");
sub firstSub{

local ($firstVar) = $_[0];

my($secondVar) = $_[1];
print("firstSub: firstVar = $firstVar\n");
print("firstSub: secondVar = $secondVar\n\n");
secondSub();
print("firstSub: firstVar = $firstVar\n");
print("firstSub: secondVar = $secondVar\n\n");
}
sub secondSub{
print("secondSub: firstVar = $firstVar\n");
print("secondSub: secondVar = $secondVar\n\n");
$firstVar = "ccccC";
$secondVar = "DDDDD";
print("secondSub: firstVar = $firstVar\n");
print("secondSub: secondVar = $secondVar\n\n");
}

Output:

G:\perl_programs>perl perl_scope1.pl
firstSub: firstVar = AAAAA
firstSub: secondVar = BBBBB

secondSub: firstVar = AAAAA
secondSub: secondVar =


secondSub: firstVar = ccccC
secondSub: secondVar = DDDDD

firstSub: firstVar = ccccC
firstSub: secondVar = BBBBB


Analysis:

As you may see the firstvar declared as local scope is visible in secondSub routine
But secondVar declared as my scope is not visible in the routine secondSb and it is empty.
 And the other thing you may notice is firstVar variable intialized as "ccccC" overwrites the value in the block from which it was called.But in the case of secondVar variable it is not overwritten.

Saturday, July 23, 2011

joining the lines in file using comma perl

Content of list.txt:

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:

#!/usr/bin/perl
use File::Copy;
open(FH,";
close(FH);
#For creating the temp file and adding the line no
open(FH1,">list.txt.bak");
$dd=join(',',@ddd); # for joining the lines in the file
$dd =~ s/\n//sg; # for removing the newline character
print FH1 $dd;
close(FH1);
move("list.txt.bak","list.txt") or die "cannot move";
# for moving the temp file to the original files
unlink("list.txt.bak") or die "cannot delete the file";
# for removing the temp file

Content of the list.txt after execution of perl file:

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

Analysis:
Here i am trying to join all the lines of the file list.txt and separate the lines by comma.To join all the lines i have used join command and replaced "\n" with space using substution in perl.

Adding line no in the files perl

Content of the list.txt:

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 perl file:

#!/usr/bin/perl
use File::Copy;
open(FH,"<list.txt");

@ddd=<FH> ;
close(FH);
#For creating the temp file and adding the line no
open(FH1,">list.txt.bak");
$size=scalar(@ddd);
for ( $i=0;$i<$size;$i++)
{
$ddd[$i]=~ m/(.*)/;
$dd="$i: "."$1"."\n";
print FH1 $dd;
}
close(FH1);
move("list.txt.bak","list.txt") or die "cannot move";
# for moving the temp file to the original files
unlink("list.txt.bak") or die "cannot delete the file";
# for removing the temp file

Content of the list.txt after execution of the perl file:

0: Hi gopal,how are you
1: Hi james,how are you
2: Hi,how are you
3: Hi Thomas,how are you
4: Hi Manjula,how are you
5: Hi karthik,how are you

Analysis:

Here i have tried add the line no in the file list.txt.For this i have created a tmp file
list.txt.bak and added the line no in those file by using the array index and later replaced the original file list.txt with tmp file:

To match a pattern not having a word inbetween perl

To match a pattern not having a word in between

For example if you want to match a pattern "Hi [person's name],how are you" and person should not be karthik like "Hi karthik,how are you"
and the person's name can be anything else.


Content of list.txt:

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 perl file:

#!/usr/bin/perl
open(FH,")
{
if ($_=~ m/Hi\s+((?!karthik)\w)*\,how are you/ )
{
print;
}
}

Output:

G:\perl_programs>perl perl_avoidword.pl
Hi gopal,how are you
Hi james,how are you
Hi Thomas,how are you
Hi Manjula,how are you

G:\perl_programs>


Analysis:
Here the important part of it is ((?!karthik)\w)*  which specifies karthik should not be there in between but any other word can be there specified by \w


To extract all occurence of word from string perl

#To extract occurence of word from string
#To extract a occurence of word from a string it is very easy in perl.We need to search the occurence in global way.
#For example to extract all occurence of emailid from a string
Content of the perl file:

#!/usr/bin/perl
$dd='karthik karthik@gmail.com lijo lijo@gmail.com james james@gmail.com thomas thomas@gmail.com';
while ( $dd =~ /\s+(\S*\@\S*.com)\s+/g )
{
print $1."\n";
}


output:

G:\perl_programs>perl perl_occurence.pl
hellokarthik@gmail.com
lijo@gmail.com
james@gmail.com

G:\perl_programs>

Analysis:
Here i have used the pattern /\s+(\S*\@\S*.com)\s+/g  to extract all email-ids from the scalar $dd.Here g signifies globally match all the email -ids from the string. 

Tuesday, July 19, 2011

find:bad option find: path-list predicate-list error

This error happens when the wildcard character in your find command expands.
This mainly happens when you run inside a script rather than from a command prompt.
For example inside the perl program you have something like:


@files=`find . -name *C* `;

When you run this program it will through this error:
find:bad option
find:path-list predicate list

Solution to it is enclose the wildcards within single quote or double quotes like this
to prevent the error:

@files=`find . -name '*'C'*' `;
(or)
@files=`find . -name "*C*"`;

Finding the occurence of word in line perl

Perl Program:

#!/usr/bin/perl
$line = "The most hello great hello great important";
@array=split(/hello/,$line);
$count=scalar(@array);
$count = $count -1 ;
print "The no of occurences of hello in line is $count";

OUTPUT:

G:\perl_programs>perl perl_no_of_words.pl
The no of occurences of hello in line is 2
G:\perl_programs>


Analysis:
Here is split function is used to split line based on the word hello.And the no of split words will be 1 more than the occurence of the word.So we need to subtract 1.

Monday, July 18, 2011

goto keyword perl

goto keyword allows you to jump to a particular LABEL declared in the program.But usuage of goto is not recommended as it will spoil the code login.It is better to avoid it

redo keyword perl

redo keyword:
The redo keyword causes Perl to restart the current Statement block.It does not either intialize or increment or decrement.It is
usually used in case of the statements where the input is from another file or from the keyboard.


Content of the Perl file:

{
print ("what is your name? " );
$name=;
chop($name);
content of the perl file:
if ( ! length($name)) {
print ("Zero length name please try a valid name");
redo;
}
print ("Thank you ".uc($name)."\n");

}

OUTPUT:

G:\perl_programs>perl perl_redo.pl
what is your name? karthik
Thank you KARTHIK

G:\perl_programs>perl perl_redo.pl
what is your name?
Zero length name please try a valid namewhat is your name?
Zero length name please try a valid namewhat is your name? kkkk
Thank you KKKK

G:\perl_programs>
As you may see when you give no name it restarts the block to ask the name again.

next keyword perl

The next keyword lets you skip the rest of the statement block and start the next iteration.
It can be used in cases where you want processing only for selected array elements and want
to ignore the rest.



Content of the perl file is:
@array=(1..10);
foreach $var(@array)
{

next if ( $var == 5 || $var == 6 );
print "The var value is $var"."\n";
}

OUTPUT :

G:\perl_programs>perl perl_next.pl
The var value is 1
The var value is 2
The var value is 3
The var value is 4
The var value is 7
The var value is 8
The var value is 9
The var value is 10

G:\perl_programs>
In this case as you may see the var value 5 and 6 are not printed due to the next statement.

last keyword perl

The last keyword is used if you want to break out of the statement block.
This can be used in cases when you iterate through the variables in a array,when you
found the value you want to break out of the loop.


Example:

@array=(1..10);
foreach $var(@array)
{
last if($var==5);
print "The value of var is $var"."\n";
}

OUTPUT:

G:\perl_programs>perl perl_last.pl
The value of var is 1
The value of var is 2
The value of var is 3
The value of var is 4

G:\perl_programs>
Here as you may see from the program it breaks the loop when the value of the $var reaches 5.

Foreach loop perl

It is a special form of for loop in which is specially used for arrays.
It is used to iterate through each element of the array.


SYNTAX:

foreach LOOP_VAR (ARRAY) {
STATEMENTS
}
In this case for each iteration a element of the ARRAY is stored in LOOP_VAR

Example:

@array=(1..10);
foreach $var(@array)
{
print "The var value is $var"."\n";
}

Output:

G:\perl_programs>perl perl_foreach.pl
The var value is 1
The var value is 2
The var value is 3
The var value is 4
The var value is 5
The var value is 6
The var value is 7
The var value is 8
The var value is 9
The var value is 10

G:\perl_programs>

For Loop perl

For loop is mainly used to loop through the STATEMENTS a specific number of times.
You can use it when you want to execute statement specific number of times.


SYNTAX:

For loops:
for(INITALIZATION;CONDITION;INCREMENT/DECREMENT)
{
STATEMENTS
}

In this case the intialization happens first,and the condition is checked,when the condition is passed it executes the statements,Else it comes out
And after executing the Statement,it increments or decrements and checks the condition.If condition passes it again executes else it
comes out.


Example:

for ( $var = 0; $var < 10; $var ++) { print "The var value is $var"; }

Output:

G:\perl_programs>perl perl_for.pl
The var value is 0
The var value is 1
The var value is 2
The var value is 3
The var value is 4
The var value is 5
The var value is 6
The var value is 7
The var value is 8
The var value is 9

G:\perl_programs>

while loop perl

while loop is used to repeat block of statement

Syntax :
It can be used as do-while loop or simply while loop
1)

do
{
STATEMENTS
}while (CONDITION);
In this case the statements gets executed atleast once.For the next iteration the condition in the until has to be true.

2)

while(CONDITION)
{
STATEMENTS;
}
In this case the statements will be executed only when the condition is true.

Example:

1)
Content of the perl file:

$num=20;
do
{
print "the num is $num";
$num++;
}
while($num < 30 )

OUTPUT:

G:\perl_programs>perl perl_while.pl
the num is 20
the num is 21
the num is 22
the num is 23
the num is 24
the num is 25
the num is 26
the num is 27
the num is 28
the num is 29

G:\perl_programs>
2)
Content of the perl file:

$num=20;
while( $num < 30) { print "the num is $num"; $num++; }

OUTPUT: 

G:\perl_programs>perl perl_while.pl
the num is 20
the num is 21
the num is 22
the num is 23
the num is 24
the num is 25
the num is 26
the num is 27
the num is 28
the num is 29

G:\perl_programs>

The main differece between the two in the case of do loop statement will be executed atleast one irrespective of the condition is true or false.

until loop perl

until loop is used to repeat block of statement till the condition is false.

Syntax :
It can be used as do-until loop or simply until loop
1)

do
{
STATEMENTS
}until (CONDITION);
In this case the statements gets executed atleast once.For the next iteration the condition in the until loop has to be false.

2)

until(CONDITION)
{
STATEMENTS;
}
In this case the statements will be executed only when the condition is true.

Example:

1)
Content of the perl file:

$num=20;
do
{
print "the num is $num"."\n";
$num++;
}
until($num >30 )

OUTPUT:

G:\perl_programs>perl perl_until.pl
the num is 20
the num is 21
the num is 22
the num is 23
the num is 24
the num is 25
the num is 26
the num is 27
the num is 28
the num is 29
the num is 30
G:\perl_programs>
2)
Content of the perl file:

$num=20;
until( $num > 30) { 

 print "the num is $num"."\n";
 $num++; 
}

OUTPUT: 

G:\perl_programs>perl perl_until.pl
the num is 20
the num is 21
the num is 22
the num is 23
the num is 24
the num is 25
the num is 26
the num is 27
the num is 28
the num is 29
the num is 30
G:\perl_programs>

The main differece between the two in the case of do loop statement will be executed atleast one irrespective of the condition is true or false.

Sunday, July 17, 2011

if statement and syntax perl

if statement:
If statement is mainly used by for decision making.
There are actually 3 ways it can be used.
Different Syntax which can be used:

1)

if (CONDITION) {
#code block to be executed
}
2)

if (CONDITION) {
#code block to be executed
}
else {
#code block to be executed if condition fails
}
3)

if (CONDITION_ONE) {
# code block to be executed if CONDITION_ONE passes
}
elsif (CONDITION_TWO)
{
#code block to be executed if CONDITION_TWO passes and CONDITION_ONE FAILS
}
else
{
# code block to be executed if both conditions fails
}
Example:

1)

$number=10;
if ( $number = 10 )
{
print "The number is 10";
}

Output:
The number is 10

2)

$number=20;

if ( $number = 10 )
{
print "The number is 10";
}
else
{
print "The number is not 10";
}
Output:
The number is not 10

3)

$number=20;
if ( $number = 10 )
{
print "The number is 10";
}
elsif ($number =20 )
{
print "The number is 20";
}

else
{
print "the number is not 10 and 20";
}

Output:
The number is 20;


To view the file information perl

To view the file information for a file in perl use the following statement:

Content of the Perl File:
use POSIX qw(strftime);
use File::stat;
my $sb = stat("test.txt");
print "Size: ".$sb->size."\n";
print "mtime in unreadable format:". $sb->mtime."\n";
$mtime=$sb->mtime;
my @systime =  localtime($mtime) ;
 my $str = strftime( "%a %b %e %H:%M:%S %Y", @systime );
print "mtime in readable format:".$str."\n";
 print "chmmod :".$sb->mode ."\n";
printf "Permissions are %04o\n", $sb->mode & 07777;
print "ctime :". $sb->ctime."\n";
 #ctime can also be converted into correct format similarly as did for mtime

We can access all the other file attributes given below by using $sb->needed file attribute as done for attribtes like mtime,ctime.

  1. 0 dev device number of filesystem
  2. 1 ino inode number
  3. 2 mode file mode (type and permissions)
  4. 3 nlink number of (hard) links to the file
  5. 4 uid numeric user ID of file's owner
  6. 5 gid numeric group ID of file's owner
  7. 6 rdev the device identifier (special files only)
  8. 7 size total size of file, in bytes
  9. 8 atime last access time in seconds since the epoch
  10. 9 mtime last modify time in seconds since the epoch
  11. 10 ctime inode change time in seconds since the epoch (*)
  12. 11 blksize preferred block size for file system I/O
  13. 12 blocks actual number of blocks allocated

This was reffered from http://perldoc.perl.org/functions/stat.html

Output :

G:\perl_programs>perl perl_size.pl
Size: 42
mtime in unreadable format:1310916921
mtime in readable format:Sun Jul  21:05:21 2011
chmmod :33206
Permissions are 0666
ctime :1310916921

G:\perl_programs>

Read and write in the same file perl

Content of hello.dat file  before running the command:

hello how are you
wonderful beautiful
great
award great
awesome

Content of the perl file:

open(FILE,"+<hello.dat");
# "+<"  option has to be used for read and writing to the file
@lines=<FILE>;  
foreach(@lines)
{
chop;
print;   # it is same as print $_;
print "\n";
}
print FILE "\n"."karthik";
close(FILE);



Output Execution:
G:\perl_programs>perl perl_file.pl
hello how are you
wonderful beautiful
great
award great
awesom

G:\perl_programs>

Content of the hello.dat file after execution:

hello how are you
wonderful beautiful
great
award great
awesome
karthik

To repeat words in perl

This makes use of the repeatation operator "x" to repeat the words

Content of the perl file:

$dd="hello";
$ss="$dd "x 5;
print $ss;

Output:

G:\perl_programs>perl perl_repeat.pl
hello hello hello hello hello
G:\perl_programs>

To find the filesize in perl

Solution 1:
For example for file test.txt.It is done by using the stat function in File module

use File::stat;
my $filesize = stat("test.txt")->size;
print "Size: $filesize\n";

Output:

Size: 42

Solution 2 :
It is done using the -s option

my $dd= -s "test.txt";
print "Size : $dd";

Output:

Size: 42

Call by reference perl

When you call by reference ,you use directly the scalar reference and so any change in the function causes the change to happen in the main program.

Content of the perl file:

@array=("hello","aaaa","lll","ggg");
print "The content of array element 0 and 1 before function call is $array[0] and $array[1]"."\n";
function(@array);
print "The content of array element 0 and 1 after function call is $array[0] and $array[1]";
sub function()
{
$_[0]="Great";#this is the scalar reference of the first element in the array.
$_[1]="awesome";#this is the scalar reference of the second element in the array.
}

Output:

G:\perl_programs>perl perl_pass_by_reference.pl
The content of array element 0 and 1 befoe function call is hello and aaaa
The content of array element 0 and 1 after function call is Great and awesome
G:\perl_programs>

finding no of array elements perl

Content of the perl file:

@array=("hello","aaaa","lll","ggg");
print "The no of elements in the array is ".scalar(@array)."\n";
#it can also be done by this way
$no=@array;
print "The no of elements in array is ". $no;

Output:

G:\perl_programs>perl perl_array_no.pl
The no of elements in the array is 4
The no of elements in array is 4


G:\perl_programs>

Tuesday, July 12, 2011

Deleting the backup files in the directory perl

Use simply

unlink(<*.bak>);  
Here i have assumed the backup files to end with .bak this wildcard can be changed as per your requirement
in the perl script and execute it will delete all the files ending up .bak in the current directory


you can also execute from the command line as follows:

G:\perl_programs>perl -e "unlink(<*.bak>);"

Globbing concept in perl

Perl supports globbing which helps you to find files with wildcard characters.
To print all the files starting with "f" in the current directory use the script below


Perl script:

@array=; # this can be modified to your need
print "@array\n";

OUTPUT:

G:\perl_programs>perl perl_globbing.pl
function_perl.pl function_sendarray.pl


This concept can be also used to delete all the backup files ending with .bak in the current directory using the following lines:


unlink(<*.bak>);

Redirecting the input from another file perl

Content of the data:

 root> cat data
while(<STDIN>)
{
print();
}
while(<>)
{
print();
}
root> 

Content of the Perl File:
Perl file:

root> cat kk.pl
while(<>)
{
print();
}

Execution of the perl file:

root> perl kk.pl < data
while(<STDIN>)
{
print();
}
while(<>)
{
print();
}
root>

Monday, July 11, 2011

inserting at a particular line no shell

content of hello.data file before insertion:

acer@ubuntu:/tmp$ cat hello.data
hello
how are you
wonderful
great awesome
May be might be

Script file:

acer@ubuntu:/tmp$ cat dd.sh
#!/bin/bash
sed -i '5ikarthik' /tmp/hello.data 

acer@ubuntu:/tmp$ ./dd.sh

Content of hello.data file after insertion:

acer@ubuntu:/tmp$ cat hello.data
hello
how are you
wonderful
great awesome
karthik
May be might be
acer@ubuntu:/tmp$

Reading a file and writing to stdout shell

content of hello.dat file:

acer@ubuntu:/tmp$ cat hello.data
hello
how are you
wonderful
great awesome
May be might be
acer@ubuntu:/tmp$ 

content of script file:

acer@ubuntu:/tmp$ cat hh.sh
#!/bin/bash
while read line ;do
echo $line ;
done < /tmp/hello.data
acer@ubuntu:/tmp$
OUTPUT:

acer@ubuntu:/tmp$ ./hh.sh
hello
how are you
wonderful
great awesome
May be might be

Converting lowercase to uppercase and uppercase to lowercase

content of perl_case.pl:

$name="HhEesssSSSSS";
#converting into uppercase
$capital=uc($name);
print "the name in uppercase is $capital.\n";
$lowercase=lc($name);
print "the name in lowercase is  $lowercase.\n";

OUTPUT:

G:\PERL_P~1>perl perl_case.pl
the name in uppercase is HHEESSSSSSSS.
the name in lowercase is  hheessssssss.
G:\PERL_P~1>

Writing to a file perl

perl_fileout.pl:

open(FILE,">>hello_out.dat");
print FILE "hello howw are you";
print FILE "wonderful";
print FILE "awesome";
print FILE "great";
close(FILE);
G:\perl_programs>perl perl_fileout.pl
G:\perl_programs>


When you run this program hell_out.dat is created in the current directory  with the following content:

hello howw are youwonderfulawesomegreat

the following program for making lines come in a new line:
open(FILE,">>hello_out.dat");
print FILE "hello howw are you"."\n";
print FILE "wonderful"."\n";
print FILE "awesome"."\n";
print FILE "great"."\n";
close(FILE);

Reading a File and printing to STDOUT Perl

content of hello.dat:

hello how are you
wonderful beautiful
great
award great
awesome

content of Perl file:

perl_file1.pl
open(FILE,"<hello.dat");
@lines=<FILE>;      
close(FILE);
foreach(@lines)
{
chop;
print;   # it is same as print $_;
print "\n";
}

output:

G:\perl_programs>perl perl_file.pl
hello how are you
wonderful beautiful
greataward great
awesom
G:\perl_programs>

Sunday, July 10, 2011

Callig parent method from child class


Perl Script:


package Inventory_item;
sub new {
$class=shift;
%params=@_;
bless {
"PART_NUM" => $params{"hh"},
"PART_VAL" => $params{"qq"}
},$class;
}
package Coloritem;
@ISA=("Inventory_item");
@PARENT::ISA=@ISA;  # this is the statement needed for calling parent method from child class
sub new {
my($class)=shift;
my(%params)=@_;
my($self)=$class->PARENT::new(@_);
$self->{"INK_COLOR"}=$params{"INK_COLOR"};
return($self);
}
package main;
$item=Coloritem->new("hh","22222","qq","3232323232","INK_COLOR","54545555");
print("The part num is ".$item->{'PART_NUM'} ."\n");
print ("The quantity is ".$item->{'PART_VAL'} ."\n");
print ("the  ".$item->{'INK_COLOR'}."\n");


OUTPUT:


G:\perl_programs>perl perl_parent.pl
The part num is 22222
The quantity is 3232323232
the  54545555
G:\perl_programs>

adding a path to the environment

Perl Script:

#ENV is a hash in perl.
#You can access as it a simple hash
#For instance to add a path in the environment variable PATH in the OS execute the following program:


$ENV{'PATH'} = "G:\\perl_programs;"."$ENV{'PATH'}";
print "$ENV{'PATH'}";

OUTPUT:

G:\perl_programs>perl env_path.pl
G:\perl_programs;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Prog
ram Files\QuickTime\QTSystem\;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:
\strawberry\perl\bin
G:\perl_programs>

displaying env variables set

Perl Script:

foreach $key (keys(%ENV)) {
    printf("%-10.10s: $ENV{$key}\n", $key);
}

Output:

PROMPT    : $P$G
NUMBER_OF_: 4
FP_NO_HOST: NO
HOMEPATH  : \Documents and Settings\acer
PATH      : C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Pr
iles\QuickTime\QTSystem\;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;
wberry\perl\bin
USERDOMAIN: ACER-5D58E53AB3
TERM      : dumb
PROCESSOR_: x86
QTJAVA    : C:\Program Files\Java\jre1.6.0_02\lib\ext\QTJava.zip
TEMP      : C:\DOCUME~1\acer\LOCALS~1\Temp
PROCESSOR_: 2502
SYSTEMDRIV: C:
SYSTEMROOT: C:\WINDOWS
COMSPEC   : C:\WINDOWS\system32\cmd.exe
LOGONSERVE: \\ACER-5D58E53AB3
SESSIONNAM: Console
FTP_PASSIV: 1
WINDIR    : C:\WINDOWS
PROCESSOR_: 6
USERNAME  : acer
PROCESSOR_: x86 Family 6 Model 37 Stepping 2, GenuineIntel
ALLUSERSPR: C:\Documents and Settings\All Users
COMPUTERNA: ACER-5D58E53AB3
CLASSPATH : .;C:\Program Files\Java\jre1.6.0_02\lib\ext\QTJava.zip
TMP       : C:\DOCUME~1\acer\LOCALS~1\Temp

time difference perl objects

Perl Script:

package Timer;
sub new
{
my $self=shift;
$dd={};
$dd{"created"}=time;
print "the time now is $dd{'created'}"."\n";
bless $dd,$self;
}
sub diff
{
my $self=shift;
my $ff= time - $self->{created};
}
package main;
$timer=new Timer;
sleep 4;
$dd=$timer->diff;
print "time elapsed is $dd"

Output:

G:\perl_programs>perl perl_object1.pl
the time now is 1310282015
time elapsed is 1310282019
G:\perl_programs>

sending array as arguments

Perl Script

sub myfunc
{
my @a = @{shift()};
print "@a";
}
package main;
@aa=("hello","aaaaa");
&myfunc (\@aa);

Output:

G:\perl_programs>perl function_sendarray.pl
hello aaaaa
G:\perl_programs>

Saturday, July 9, 2011

inheritance example 2

Perl Script:

#usr/bin/perl
package Person;
sub new
{
my $pkg=shift;
bless{ @_ },$pkg;
}
package Student;
@ISA=qw(Person);
$ddd=new Person(name=>"jjjjj",age=>55);
$aaa=new Student(name=>'ssss',id=>55,class=>"tenth");
print $ddd->{name};
print $aaa->{name};

Output:

jjjjj
ssss

Inheritance example 1

PERL SCRIPT:

package A;
sub new { bless {}, shift };
sub A_Method {
print "A_Methos\n";
}
package B;
@ISA=qw(A);
sub B_Method {
print "B_Method\n";
}
sub Method {
print "Method (in B)\n";
}
package C;
@ISA = qw(B);
sub C_Method{
print "C_Method\n";
}
sub Method {
print "Method (in B)\n";
}
package main;
$a = new A;
#here the method first converted A::new(A) in the format of class::Method('class','arg1','arg2')
$b=new B;
$c=new C;
$c->C_Method();
$c->Method();
$c->B_Method();h
$c->A_Method();
$a->Method();  # this returns error as  object $a does not contain method Method();

OUTPUT:

g:\perl_programs>perl perlinherit.pl
C_Method
Method (in B)
B_Method
A_Method
Can't locate object method "B_Method" via package "A" at perlinherit.pl line 43.

Tuesday, July 5, 2011

Debugging in perl

To see the warning present in your perl script run your  script with -w as as follows:

perl -w  karthik.pl

It will help to find out the error in your script.
Next fine way of finding the errors is stepping through the program line by line:
For that you can run the script with  -d option.

perl -d inheritance.pl
These options will be handy for that:
s        -  for moving through the program step by  step.Even when it moves into a function it moves line by line.It is very slow maybe helpful to see how the code is executed.

n       -  it executes the next statement in the script .Although all function calls are executed it does not follow the execution path inside a function.It helps to move quicker than the s option.

c     -  it executes entire script untill it encounters a break point before the script ends.
          you can also use this option to continue untill the line number after c.
          c 40   - makes the debugger to execute untill line number 40.

No command(enter)  - makes it to execute previous n or s command previously executed.
example:
  DB<1> s
main::(perl_inheritance.pl:24): $a = new A;
  DB<1> s
A::new(perl_inheritance.pl:2):  sub new { bless {}, shift };
A::new(perl_inheritance.pl:3):  sub A_Method {
  DB<1> s
main::(perl_inheritance.pl:26): $b=new B;
  DB<1> n
main::(perl_inheritance.pl:27): $c=new C;
Here as you may see when you use s option the debugger moves into the new method
but when use the n option it does not go into the execution path of the method and moves next line after the method.

  DB<1> c
C_Method
Method (in B)
B_Method
A_Methos
Method (in B)
Debugged program terminated.  Use q to quit or R to restart,
  use o inhibit_exit to avoid stopping after program termination,
  h q, h R or h o to get additional info.
when you use c option it simply ends as we have not set any breakpoints


Seeing the trace how the program gets executed:

For that you have to turn on the trace mode:
typing t and pressing enter turns on the trace and typing t again and pressing Enter turns off the trace.
  DB<1> t
Trace = on
  DB<1> c
C::(perl_inheritance.pl:15):    @ISA = qw(B);
C::(perl_inheritance.pl:16):    sub C_Method{
main::(perl_inheritance.pl:24): $a = new A;
A::new(perl_inheritance.pl:2):  sub new { bless {}, shift };
A::new(perl_inheritance.pl:3):  sub A_Method {
main::(perl_inheritance.pl:26): $b=new B;
A::new(perl_inheritance.pl:2):  sub new { bless {}, shift };
A::new(perl_inheritance.pl:3):  sub A_Method {
main::(perl_inheritance.pl:27): $c=new C;
A::new(perl_inheritance.pl:2):  sub new { bless {}, shift };
A::new(perl_inheritance.pl:3):  sub A_Method {
main::(perl_inheritance.pl:28): $c->C_Method();
C::C_Method(perl_inheritance.pl:17):
17:     print "C_Method\n";
C_Method
main::(perl_inheritance.pl:29): $c->Method();
C::Method(perl_inheritance.pl:20):      print "Method (in B)\n";
Method (in B)
main::(perl_inheritance.pl:30): $c->B_Method();
B::B_Method(perl_inheritance.pl:9):
9:      print "B_Method\n";
B_Method
main::(perl_inheritance.pl:31): $c->A_Method();
A::A_Method(perl_inheritance.pl:4):
4:      print "A_Methos\n";
A_Methos
main::(perl_inheritance.pl:32): $c->Method();
C::Method(perl_inheritance.pl:20):      print "Method (in B)\n";
Method (in B)
Debugged program terminated.  Use q to quit or R to restart,
  use o inhibit_exit to avoid  stopping after program termination,
  h q, h R or h o to get additional info.
  DB<1>

Setting  the breakpoint:

b   - sets the  breakpoint
b followed by the line no sets the breakpoint in that lineno.
  DB<1> b 27
  DB<2> c
main::(perl_inheritance.pl:27): $c=new C;

As you may see i set the breakpoint at line no 27 and use option c it stops at the lineno 27.

D  - using this option deletes all the breakpoints set.you can also delete individual breakpoints using option d  followed by lineno where breakpoint is set.

For setting action:

Action is used when you want to print any  variable or string before a line no:
It can be done using the following syntax:
a  10 print("$count");

By this $count value is printed before line no.
G:\perl_programs>perl -d perl_inheritance.pl
Loading DB routines from perl5db.pl version 1.33
Editor support available.
Enter h or `h h' for help, or `perldoc perldebug' for more help.
B::(perl_inheritance.pl:7):     @ISA=qw(A);
B::(perl_inheritance.pl:8):     sub B_Method {
  DB<1> a 27 print "hello here is the action"."\n"
  DB<2> c
hello here is the action
C_Method
Method (in B)
B_Method
A_Methos
Method (in B)
Debugged program terminated.  Use q to quit or R to restart,
  use o inhibit_exit to avoid stopping after program termination,
  h q, h R or h o to get additional info.
hello here is the action
A  - deletes all actions.

Options for displaying information:
L -  lists all breakpoints and actions.

l  - prints part of the script
    l  - prints 10 lines of script
    l  <lineno>  - prints the particular line in the script.
    l   5+4  - lists 4 lines starting with line  5
    l   4-8     - lists lines from 4 to 8

S  - prints all function names defined including those in external scripts

T  - prints the stack trace.The trace of the entire program how it gets executed.

V  -  prints the variables defined from all packages and modules loaded

X  -  list variables only in the current package

Finally
q   - can be used to quit from the debugger


Saturday, July 2, 2011

ENV in perl to view the environmental variables set


The program to view the environmental variables set:
foreach $key (keys(%ENV)) {
    printf("%-10.10s: $ENV{$key}\n", $key);
}

ouput:
HOMEPATH  : \Documents and Settings\acer
PATH      : C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Pr
iles\QuickTime\QTSystem\;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;
wberry\perl\bin
USERDOMAIN: ACER-5D58E53AB3
TERM      : dumb
PROCESSOR_: x86
QTJAVA    : C:\Program Files\Java\jre1.6.0_02\lib\ext\QTJava.zip
TEMP      : C:\DOCUME~1\acer\LOCALS~1\Temp
PROCESSOR_: 2502
SYSTEMDRIV: C:
SYSTEMROOT: C:\WINDOWS
COMSPEC   : C:\WINDOWS\system32\cmd.exe
LOGONSERVE: \\ACER-5D58E53AB3
SESSIONNAM: Console
FTP_PASSIV: 1
WINDIR    : C:\WINDOWS
PROCESSOR_: 6
USERNAME  : acer
PROCESSOR_: x86 Family 6 Model 37 Stepping 2, GenuineIntel
ALLUSERSPR: C:\Documents and Settings\All Users
COMPUTERNA: ACER-5D58E53AB3
CLASSPATH : .;C:\Program Files\Java\jre1.6.0_02\lib\ext\QTJava.zip
TMP       : C:\DOCUME~1\acer\LOCALS~1\Temp

ENV in perl to view the environmental variables set


The program to view the environmental variables set:
foreach $key (keys(%ENV)) {
    printf("%-10.10s: $ENV{$key}\n", $key);
}

ouput:

HOMEPATH  : \Documents and Settings\acer
PATH      : C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Pr
iles\QuickTime\QTSystem\;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;
wberry\perl\bin
USERDOMAIN: ACER-5D58E53AB3
TERM      : dumb
PROCESSOR_: x86
QTJAVA    : C:\Program Files\Java\jre1.6.0_02\lib\ext\QTJava.zip
TEMP      : C:\DOCUME~1\acer\LOCALS~1\Temp
PROCESSOR_: 2502
SYSTEMDRIV: C:
SYSTEMROOT: C:\WINDOWS
COMSPEC   : C:\WINDOWS\system32\cmd.exe
LOGONSERVE: \\ACER-5D58E53AB3
SESSIONNAM: Console
FTP_PASSIV: 1
WINDIR    : C:\WINDOWS
PROCESSOR_: 6
USERNAME  : acer
PROCESSOR_: x86 Family 6 Model 37 Stepping 2, GenuineIntel
ALLUSERSPR: C:\Documents and Settings\All Users
COMPUTERNA: ACER-5D58E53AB3
CLASSPATH : .;C:\Program Files\Java\jre1.6.0_02\lib\ext\QTJava.zip
TMP       : C:\DOCUME~1\acer\LOCALS~1\Temp


ENV in perl to add path


ENV is a hash in perl.
You can access as it a simple hash
For instance to add a path in the environment variable PATH in the OS execute the following program:

env_path.pl:
$ENV{'PATH'} = "G:\\perl_programs;"."$ENV{'PATH'}";
print "$ENV{'PATH'}";


output:
G:\perl_programs>perl env_path.pl
G:\perl_programs;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Prog
ram Files\QuickTime\QTSystem\;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:
\strawberry\perl\bin
G:\perl_programs>

This added path will go off once the perl program is executed.It will be available only to the child process