Sei sulla pagina 1di 3

Sample PERL Programs

1. Welcome message

#!perl/bin

print "Sample perl prg";

2. Getting and Adding Two Numbers:

#!perl/bin #print "Enter two numbers "; $n1 = <>;

chomp($n1);

$n2=<>;

chomp($n2);

$n3 = $n1 + $n2; #print "Given numbers are #print $n1,$n2; print "$n1 + $n2 = $n3";

";

3. For loop #!perl/bin print "Enter a number $num=<>; chomp($num);

";

for($i=1;$i<=$num;$i++)

{

print $i,"\n";

}

4. User Defined Function

#!perl/bin print "Enter a number $n = <>;chomp($n);

sub fact() {$f =1;

for($i=1;$i<=$_[0];$i++)

{ $f = $f * $i;} return ($f);

}

$fact_n=&fact($n); print "Fact of $n = $fact_n";

";

5. Array #!perl/bin print "Enter a numer"; $num=<>;

chomp($num); @arr = 1 $num;

print "content of array is foreach $val(@arr)

\n";

 

{

print $val,"\n";

}

6.

File Write #!perl/bin

open($fh,">f1_text.txt");

print $fh 10,"AAA\n"; print $fh 20,"BBBBB\n"; print "data written into file"; close($fh);

7.

File Read #!perl/bin print "Enter file name\n"; $fn = <>; chomp($fn); open($fh,$fn); print "Content of file is\n"; @file_cont = <$fh>; print @file_cont; #while($f = <$fh>) #{ chomp($f); #print $f;} close($fh);

8.

File Read Loop:

#!perl/bin print "enter file name to display

\n";

$fname = <>; chomp($fname); print "Content of the above file is open($fh,$fname); while($line=<$fh>)

\n";

{

print $line;

}

close($line);

9.

Display File Content dynamically #!perl/bin

print "Enter file name "; $fn = <>; chomp($fn); open($fh,$fn); print "Content of the file\n"; @cont_file = <$fh>; print @cont_file; close($fh);