Friday, July 2, 2010

perl examples

Example 1: Input two number, output sum

------------------------------------------------
#!/usr/bin/perl

$doagain = "yes";

while
($doagain eq "yes") {
$x = &getnumber;
$y = &getnumber;

$z = $x + $y;

print "$x + $y = $z\n";

print "$x + $y = $z\n";

print "Do it again? (yes or no) ";
$doagain = <STDIN>;

chop($doagain);

}

sub getnumber {

print "Type in a number: \n";

$number = <STDIN>;
chop($number);

while
($number =~ /\D/){ # not non-digit, i.e digit[0-9]

print "$number is not a number\n";
print "Enter a number ";
$number = <STDIN>;

chop($number);
}

$number;
}


----------------------------------------------------------------

Example 2: find a file in a directory and its sub-directory
--------------------------------------------------------------

#!/usr/bin/perl

#
# search for a file in all subdirectories
#
if ($#ARGV != 1) {
print "usage: find_file filename directory\n";
exit;
}

$filename = $ARGV[0]; #first argument

# look in the directory
$dir = $ARGV[1]; #second argument
&searchDirectory($dir);

sub searchDirectory {
local($dir); #local variable
local(@lines);
local($line);
local($file);
local($subdir);

$dir = $_[0];
# check for permission
if(-x $dir) {

# search this directory
@lines = `cd $dir; ls -l | grep $filename`;
foreach $line (@lines) {
#\d # Any digit. The same as [0-9]
#\D # Any non-digit. The same as [^0-9]
#\s # Any whitespace character: space,
#\S # Any non-whitespace character
# tab, newline, etc

$line =~ /\s+(\S+)$/; # end of line
$file = $1;
print "Found $file in $dir\n";
}

# search any sub directories

@lines = `cd $dir; ls -l`;
foreach $line (@lines) {
if($line =~ /^d/) { # beginning of line containing d (directory)
$line =~ /\s+(\S+)$/;
$subdir = $dir."/".$1;
&searchDirectory($subdir);
}
}
}
}

----------------------------------------------------------
example 3
-----------------------------------------------

#!/usr/bin/perl
#$b and $c as strings
$b='3';

$c='2';
$a = $b . $c; # Concatenate string $b and $c
print "$a \n";

$a = $b x $c; # string $b repeated $c times
print "$a \n";
@food = ("apples", "pears", "eels");

print "$food[2] \n"; #array starting from 0
push(@food, "eggs", "lard");

print "@food \n";
foreach $morsel (@food) # Visit each item in turn
# and call it $morsel
{

print "$morsel\n"; # Print the item
print "Yum yum\n"; # That was nice
}


for
($i = 0; $i < 10; ++$i) # Start with $i = 1

# Do it while $i < 10
# Increment $i before repeating
{
print "$i\n";
}

print "Password? "; # Ask for input
$a = <STDIN>; # Get input
chop $a; # Remove the newline at end

while
($a ne "fred") # While input is wrong...
{

print "sorry. Again? "; # Ask again
$a = <STDIN>; # Get input again
chop $a; # Chop off newline again

}


if
($a)
{

print "The string is not empty\n";
}

else


{

print "The string is empty\n";
}


No comments:

Post a Comment