Sunday, October 19, 2008

Split

#!/usr/bin/perl

$str="one last challenge";

@words = split(/ +/, $str);


print($words[0] ."\n");


print($words[1] ."\n");

Saturday, October 18, 2008

Arrays

Arrays in the Perl starts with '@' symbol and it is not limited to only one data type.

#!/usr/bin/perl -w

@myArray=("Zero","one","two","three","four","five","six","seven","eight","nine");

foreach $val(@myArray)
{
print($val."\n");

}

Change the case to upper and lower

#!/usr/bin/perl -w

$str="Dasuntha";

$sub=substr $str, 2, 4;

print($sub."\n");

#convert the Uppercase

$Uppercase=uc $str;

print($Uppercase."\n");

#convert case of the first letter
$fcase=ucfirst $str;

print($fcase."\n");

$lcase=lcfirst $str;

print($lcase."\n");


#convert the Lowercase

$Lowercase=lc $str;

print($Lowercase."\n");

#chop -get the last letter
$ch=chop $str;

print($ch."\n");

Arguments are passed by reference

#!/usr/bin/perl -w
$v = 32;
print ("Value before calling the function: " . $v . "\n");
fun1($v);
print ("Value after calling the function: " . $v . "\n");
# end of program
sub fun1
{
print ("Value within the function: " . $_[0] . "\n");
$_[0] <<= 1; # shifts all bits left by 1 (like * 2)
print ("Value within the function, again: " . $_[0] . "\n");
}

Write methods in perl

Find the maximum value of the array

#!/usr/bin/perl -w

# find the maximum value of the array

$maxVal=maximum(2,10,1,9,3,12);
print("\n\nThe Maximum is : $maxVal \n");

sub maximum
{

$val=$_[0];

foreach $my(@_)
{
if($my > $val)
{
$val=$my;
print("\n Max value change to $val");
}
}
return $val;
}

last, next, redo and labels in control structures

#!/usr/bin/perl -w

for($i=0; $i<10; $i++)
{
print($i."\n");

#last will end up the loop
if($i == 7)
{
last;
}

#next
if($i == 5)
{
next;
}

}

print("\nSecond loop ...\n");

for($i=0; $i<10; $i++)
{
print($i."\n");

#next
if($i == 5)
{
next;
}

}
print("\nThird loop ...\n");

# put the label out
out:for($i=0; $i<3; $i++)
{
print($i."\n");

In:for($j=0; $j<3; $j++)
{
print($j."\n");

if($j==1)
goto out;
}
}

Friday, October 17, 2008

Find and Replace

Replace the word new with the word old. /g is used to search globally. /i is used to make case insensitive search.

#!/usr/bin/perl -w

while($_=STDIN)
{
chomp($_);

if (s/new/old/gi)
{
print($_ ."\n");
}
}


If we want to replace only the word new we can use following code.

#!/usr/bin/perl -w

while($_=STDIN)
{
chomp($_);

if (s/\bnew\b/old/gi)
{
print($_ ."\n");
}

}