Professional Documents
Culture Documents
Simplified Perl Programmes (Maybe) .
Simplified Perl Programmes (Maybe) .
Simplified Perl Programmes (Maybe) .
#!/usr/bin/perl
#search.pl
while (1)
{
print "Enter a string (say 15 chars; Ctrl-d to quit.)\n \t";
last unless (my $inp=<>);
print "Search for: ";
my $s=<>;
if ($inp =~/$s/i)
{
print "Pattern found (ignoring case). \n";
} else
{
print "Pattern not found.\n" ;
}
2)
#!/usr/bin/perl
#cwl.pl
#Counts the characters, words and lines in a file/input
print"enter paragraph:";
my @input = <>;
my $lines = @input;#array length is the no. of lines;
my $chars = 0; my $words = 0;
my $z='';
foreach $z (@input)
{
$chars+= length($z); #no. of characters in the text;
@loks = split(/[\t \,]+/,$z); #splits data when there is a tabspace or comma.
$words+=@loks;#no. of words in a line;
}
print "\n Chars=$chars; Words=$words; Lines=$lines\n";
3)
#!/usr//bin/perl
# sort.pl
# Sorts the given set of strings
print "Enter the strings to be sorted; (Ctrl-d to end input.)\n\t";
@lines=<>;
@slines=sort(@lines);
print "\n";
4)
#!/usr/bin/perl
#prime.pl
#Program checks whether the input number is prime or not.
while (1)
{
printf ("Please enter an integer(Ctrl-d to exit): ");
last unless (my $num=<>); #without this infinite loop. this helps to terminate the while loop.
checks if the input is null
my $sign = $num < 0 ? 1 : 0 ; # Check is num less than 0. if true assign 1 else assign 0
$num=abs($num);
my $ul=sqrt ($num)+1;
if ($num <= 2)
{
$num ==2 ? print "Number is prime.\n":
print "Number is neither prime nor composite.\n";
}else
{
for ($i=2; $i<=$ul; $i++)
{
$isprime = $num % $i;
last unless $isprime; #breaks when isprime is 0. i.e the number is divisable by i.
}
5)
in terminal:
perl linreg.pl < data.txt
< sumbol means reads from the particular text file.
#!/usr/bin/perl
# linreg pl
# This program fits a line of the type y = mx+ c to the given data set.
$s = 0;$sx = 0;$sx2= 0;
$sxy = 0;$sy =0;
while ($inp=<>)
{
$inp =~ s/\s+//; #remove white spaces. \s+ means white spaces.
last unless length ($inp); #terminate the loop can be removed but then n should be reduced
by 1. last command is like break statement in c
@toks = split (/[\t \n \, ]+/,$inp) ; #Read in the data splits the data wherever there is a white
space, new line or a comma
$x=$toks [0] ;
$y=$toks [1] ;
$delta = $s*$sx2-$sx*$sx;
$m = ($s*$sxy - $sx*$sy)/$delta; #Calculate m and c
$c = ($sx2*$sy -$sx* $sxy)/$delta ;