Day 2

============================================================================ Example1 : Use of shift  and unshift function
============================================================================
@os=(unix,linux,winx,minix,solaris);

<<ABC;
shift function is used to remove the 0th index of an array
syntax:
shift(@array)
This function returns the 0th element which has been removed.

unshift adds new element at the 0th index
syntax:
unshift(@array, "New value to be inserted")

ABC

print "A. @os\n";
print "B. ",scalar(@os),"\n";
$v=shift(@os);
unshift(@os,"BSD");
print "C. @os\n";
print "D. ",scalar(@os),"\n";
============================================================================ Example2 : Use of push and pop function
============================================================================
@os=(unix,linux,winx,minix,solaris);

<<ABC;
pop function is used to remove the last element of an array
syntax:
pop(@array)
This function returns the last element which has been removed.

push function will add new element at the end of the array
Syntax:
push(@array, "New value to be inserted")

ABC

print "A. @os\n";
print "B. ",scalar(@os),"\n";
$v=shift(@os);
unshift(@os,"BSD");
print "C. @os\n";
print "D. ",scalar(@os),"\n";
============================================================================ Example 3: Demo for LIFO, FIFO, FILO, LILO
============================================================================
@os=(unix,linux,winx,minix,solaris);
print "The original array elements are:  @os\n";
print "Please select from the below options: \n
A. LIFO
B. FIFO
C. FILO
D. LILO
\n";
chomp($choice=<>);

if($choice eq "A")
{
                push(@os,"BSD");
                $rv=shift(@os);
}
elsif($choice eq "B")
{
                $rv=shift(@os);
                unshift(@os,"BSD");
}
elsif($choice eq "C")
{
                $rv=pop(@os);
                unshift(@os,"BSD");
}
elsif($choice eq "D")
{
                $rv=pop(@os);
                push(@os,"BSD");
}
else
{
                print "INVALID OPTION!!!\n"
}

print "The element removed is $rv\n";
print "The array after operation is : @os";

To get the last index value of array use $# followed by array name.
Eg: $n=$#os
In the above example “os” is the name of the array and the last index is returned and saved under the variable n.

splice function:
Removes the elements designated by OFFSET(starting point) and LENGTH from an array, and replaces them with the elements of LIST, if any.
In  list context, returns the elements removed from the array.
In  scalar context, returns the last element removed, or "undef" if  no elements are removed. The array grows or shrinks as necessary.
If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array.
If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array and a LENGTH was provided, Perl issues a warning, and splices at the end of the array.

Syntax:
splice ARRAY,OFFSET,LENGTH,LIST
 splice ARRAY,OFFSET,LENGTH
 splice ARRAY,OFFSET
 splice ARRAY
 splice EXPR,OFFSET,LENGTH,LIST
 splice EXPR,OFFSET,LENGTH
 splice EXPR,OFFSET
============================================================================ Example 4: Usage of splice function
============================================================================
@os=(unix,linux,winx,minix,solaris);
print "The original array elements are:  @os\n";
print "The size of array is : ",scalar(@os),"\n";
# removes elemt 1 to 3 and insert A, B, C in place
@rv = splice(@os,1,3,(A,B,C));
print "The removed elements are : @rv\n";
print "The new array elements are: @os\n";
#removes elements from 1 to 3
@rv = splice(@os,1,3);
print "The removed elements are : @rv\n";
print "The new array elements are: @os\n";
#removes all elements starting from the index 1
@rv = splice(@os,1);
print "The removed elements are : @rv\n";
print "The new array elements are: @os\n";
#removes all elements
@rv = splice(@os);
print "The removed elements are : @rv\n";
print "The new array elements are: @os\n";
============================================================================ Example 5: #Demo for the usage of the lists, array separators:
============================================================================
@os=(unix,linux,winx,minix,solaris);
@db=("mysql","sql","DBx","DB2");
@A1=("Data1",@os,"data3",@db,"end");

$v1=@os;
print "A. $v1\n";
print "List DEMO\n";
($v1,$v2,$v3)=@os;
print "$v1 \t $v2 \t $v3\n";
($v1,@A1,$v2)=@os;
print "$v1 \t @A1 \t $v2\n";

#qw functions - quote words, this is used to initialize the arrays without comma
@A1=qw(oracle tcs cts infosys);
print "Separator DEMO\n";

print "Value of array with default separator @A1\n";
#printing the value of array with custom separator. Default is space
#In the below example we are using the semi colon : as the filed separator
$"=":";
print "Value of array with semicolon separator @A1\n";
$"="->";
print "Value of array with -> separator @A1\n";
============================================================================ Example 6: #Using grep function with arrays
============================================================================
#grep syntax
#grep(/pattern/,@INPUTARRAY)
@array=qw(bangalore chennai patna delhi);
@result=grep(/patna/,@array);
print "@result\n"
============================================================================ Example 7: #split function to convert scalar variables into arrays
============================================================================
#split function is used to convert scalar variable into an array
#syntax: split("separator",$scalar_variable)
$var="bangalore:patna:delhi:chennai";
print "1. $var\n";
print "2. Size",length($var),"\n";
@array=split(":",$var);
print "3. Array elements: @array \n";
============================================================================ Example 8: #Join function to convert array variables into scalar
============================================================================
#join function is used to convert scalar variable into an array
#syntax: join("separator",$scalar_variable)
@array=(Bangalore patna delhi Chennai);
$var=join(":",@array);
print "1. $var\n";
print "2. Size",length($var),"\n";
Reverse function: is used to reverse the array elements.
@r_array=reverse(@array)
============================================================================ Example 8: #Sort function Demo with numbers and characters
============================================================================ #Sort function: Dictionary sorting based on first character.
#syntax : @s_array=sort(@array)

@no=(10,23,45,1,2);
@SA=sort(@no);
print "@SA\n";
#ascending order
@SA1=sort({$a<=>$b}@no);
print "@SA1\n";
#descending order
@SA1=sort({$b<=>$a}@no);
print "@SA1\n";

@os=(unix,linux,winx,minix,solaris);

@sa=sort({$a cmp $b}@os);
print "Sorted order : @sa\n";

@ra=sort({$b cmp $a}@os);
print "Revers order : @ra\n";

#Note a and b are place holders and not to be changed with any other characters
============================================================================
Index <input string> <string to be searched>
This returns the first occurrence of the string to be searched in the given string. It will return -1 if no occurrence is found.
============================================================================ Example 9: Map function demo
============================================================================
<<ABC;
map BLOCK LIST
Evaluates the BLOCK or EXPR for each element of the LIST
Syntax:
map{condition1?TRUE BLOCK:FALSE BLOCK}@array_name
ABC
@number=(1..5);
my @squares=map{$_<5 ? ($_*2) : ()}@number;
print "@squares\n";

o/p:
D:\perl\day2>perl 9.pl
2 4 6 8
@ARGV is the in-built array that stores the command line arguments passed to the perl script.
============================================================================ Example 10: ARGV Demo
============================================================================
#!/usr/bin/perl

if (-e @ARGV[0])
{
        print "File @ARGV[0] exists \n";
}
else
{
        print "File @ARGV[0] does not exists\n";
}
$perl file_test hello-test.cgi
File hello-test.cgi exists
$perl file_test hello
File hello does not exists

For testing multiple arguments, map function can be used as follows:
#!/usr/bin/perl
@fstatus=map{-e $_ ?"EXISTS":"DOESNT EXISTS" }@ARGV;
print "@fstatus\n";

$perl file_test 1 hello-test.cgi 3 4
DOESNT EXISTS EXISTS DOESNT EXISTS DOESNT EXISTS
============================================================================
Note: $0 gives the program or script name similar to unix.

File Handler in Perl:
Using the file hander the file can be read and written.
To read a file:
open(FileHandler, “<FileName”)
To write into a file:
open(FileHandler,”>FileName”)
To append to a file:
open(FileHandler,”FileName”)
============================================================================ Example 11: Demo reading from a file using File Handler
============================================================================
<<ABC;
#Reading data only once
chomp($var=<>);
print "$var\n";

while($var=<>) # Reading data from keyboard in infinite loop
{
                print "$var";
}
ABC
open(FH,"test.txt");

while(<FH>) #Reading data from file
{
                chomp($_);
                print "$_\t";
}
close(FH);
============================================================================ Example 12: Check if a file exists and readable.  If it exists, display its content.
============================================================================
<<ABC;
check if the file is readable.
If yes read the file and display the content
ABC

print "Enter the file to be read: \n";
chomp($fname=<>);

if (-e $fname)
{
                if(-f $fname)
                {
                                open(FH,$fname) or die("Error:$!");
 #If the file fails to open die will exit the program
#$! will display the system error message
#we can use warn() function instead of die if we want to continue with the rest of   #program
                                while(<FH>) #Reading data from file
                                {
                                                chomp($_);
                                                ++$count;
                                                print "$count. $_\n";
                                }
                                close(FH);
                }
                else
                {
                                print "You dont have the read permission on the file $fname or its not a regular file!\n";
                }
}
else
{
                print "The file $fname does not exists\n";
}
============================================================================ Example 13: Write into a file using File handler
============================================================================
print "Enter the output file name\n";
chomp($fname=<>);

if(-e $fname)
{
                print "The file already exists, enter different file name\n";
                exit;
}

print "Enter q|Q to exit \n";

open(FH,">$fname");

while(<>)
{
                chomp;
                if("$_" eq "Quit")
                {
                                last;
                }
                else
                {
                                print FH "$. $_\n";
                }
}
close(FH);
============================================================================ Example 14: Reading from one file and writing into another
============================================================================
print "Enter the output file name\n";
chomp($ofname=<>);

if(-e $ofname)
{
                print "The file $ofname already exists\n";
                exit;
}

print "Enter input file name\n";
chomp($ifname=<>);

if(not -f $ifname)
{
                print "The file $ifname is not readable\n";
                exit;
}

open(IFH,"<$ifname") or warn($!);
open(OFH,">$ofname") or warn($!);

while(<IFH>)
{
                print OFH "$. $_\n";

}
close(IFH);
close(OFH);
============================================================================
we can also initialize like following before the read operation on the file.
$/=""; #this is is to ignore the blank lines
$/="undef"; This is to read the entire file only once
============================================================================ Example 15: This program demonstrates the use of $#<array name>. This holds the value of highest index of array.
============================================================================
@array=("test","test","test","test","test","test","test","test","test","test");
$len=scalar(@array);
print "The length of the array is $len\n";
print "The length of the array is $#array\n";
$array[20]="test";
$len=scalar(@array);
print "The length of the array is $#array\n";
$#array=4;
print "Contents of array @array\n";
print "Size of the array $#array\n";
============================================================================
Working with directories:
A directory handle is used to read the contents of a directory. You can open a directory handle using the opendir function:
opendir handle directory;
where handle is the directory handle you want to open, and directory is the name of the directory to be read.

Directory listings
• Once a directory has been opened with a dirhandle, you can read the directory contents with the readdir function:
opendir TEMPDIR, “/temp” || die;
readdir TEMPDIR;
• After you are finished with a dirhandle, you should close the handle with closedir: closedir TEMPDIR;

Storing directory contents in an array
• You will often want to read the directory contents and store the list for future use. You can assign the contents to an array just as you did with file
contents:
opendir (MDIR, “/temp”) || die;
@filelist=readdir MDIR;
closedir MDIR;
• You could then manipulate the contents of @filelist, which will have one directory line per element with most operating systems

Changing directories
• To change directories, you can use the chdir command. Changes in directory can be specified absolutely or relatively. For example:
chdir ../book;
will move up one directory level and down into the directory book.
• If you do not specify a directory argument for chdir, it will change to your home directory (if one is defined by your operating system)

Creating directories
• To create a directory, use the mkdir command with both the new directory name and the permissions are arguments: mkdir newdir, perms;
• For example:
mkdir temp, 0755 || die;
will create the directory temp under the current directory with the UNIX permissions 755
• The directory permissions use the same convention as your operating system. Not all operating systems will use permissions.

Deleting directories
• To delete directories, use the rmdir function with the pathname to the directory to be removed:
rmdir temp;
• If the directory cannot be removed, a false is returned by the operating system and can be handled with die or warn.
• You can only delete empty directories!

============================================================================ Example 15: This program demonstrates various commands to work with directories
============================================================================
mkdir(Demo,0775);

opendir(DIR,".") or die($!);
@files=readdir(DIR);
closedir(DIR);

foreach(@files)
{print `mv $_ Demo`;}
chdir(Demo);
print "Working Path is : ",`pwd`,"\n");

No comments:

Post a Comment