Shell and Perl script example

6/15/2016 12:00:00 AM

How to run perl

Same as like Bash just replace last command with “perl  filename.perl”,for perl you should save your file .perl extension.

Example1 (perl subroutine):

sub a
         print “Unix”
sub b
         print “programming”

Example2 (perl scalar variable / perl $ variable):

print “n=$n\n”;
print “n is zero\n” if ($n==0);
if($n eq “ ”)
       print STDERR “This is error”;
print “n=$n\n”;

Example3 (perl vector variable):

print “@arr[0] @arr[1]”;
foreach $v(@arr)
        print $v,”\n”;
print “Total element $#arrr”;
        print @arr[$i];

Example4 (perl shift):

@arr=”abc  def  ghi”;
print $a;

Example5 (perl split):

@arr2=split(“ ”,”I like programming”);
foreach $p(@arr)
          print $p,”\n”;

Example6(Associate array)

Index of array to be define by string [to run associate array “perl  perlFile.perl   myfile.txt”]

$animal{“dog”}=”plays stupid”;
$animal{“penguine”}=”nice animal”;
print $animal{“dog”};

Example7 (perl open / Perl read file):

while ($line=<file_handler>)
        chop  $line;
        print “line=($line)\n”

Example8 (Two file read using file handle):

open(file_handler1,”textfile.txt”)||die ”can’t open\n”;
open(file_handler2,”textfile2.txt”) ||die ”can’t open\n”;
while (($line1=<file_handler1>)||($line2=<file_handler2>))
          chop  $line1;
          chop  $line2;
          print “$line1 $line2\n”

Example9 (Execute all file using perl):

open(file_handler1,”@ARGV[0]”)||die ”can’t open\n”;
while (<file1>)
      print $_;

Example10 (Perl function / Perl subroutine):

sub Print_Arg
         print “($local_a,$local_b \n”;

Example11 (Perl retrieve file information):

($a,$b,$c)=stat(“file.txt”);                 //$a=device $b=inode $c=permission
if($c & $mask)
          print “File is writable by graph\n”;

Example12(Perl replace existing text file’s text)

Unlink $out;
print “Enter the string you want to find:\n\n”;
chop  $find;
print “Enter string you want to replace:\n\n”
chop $replace;
print  “\n Find: $find\n”;
print  “\n Replace: $replace\n”;
print “\n Confirm(Y/n)”;
        Die “Aborted \n”;
        print “Type ctl+c to Enter \n”;
Open(Input,”Unix”)||die  “Couldn’t open the file\n”;
Open(Output,”>$out”)||die “Couldn’t open the file\n”;
        print output;


Run cshell same as like bash

Example1 (tcsh Array):

Set   arr=(10 20 30)
echo  $arr[3]
echo  $#arr
echo  $arr[$#arr]

Example2 (tcsh switch):

if(-f  $argv[2]) then
echo  “File exist.copy anyway?”
case y:
                break sw
                echo  “Do nothing”
end sw
end if
echo  –n  “copying $argv[1] to $argv[2]”
cp $argv[1] $argv[2]
echo done


About Teacher

Reza Karim

Software Engineer

More about him