Welcome to perl scripting.

Let see a program in perl that will open a file and read/write it.

To open a file in read mode:

open FILEHANDLER, "/home/user1/filename.txt";

open (FILEHANDLER, "/home/user1/filename.txt");

To open a file in overwrite mode:

open (MYFILE,">/home/user1/filename.txt");

To open a file in append mode:

open (MYFILE, ">>home/user1/filename.txt");

To write some texts into a file:

print FILEHANDLER "some text";

To read the content of a file:



To Close a file :

close (MYFILE);

So now, we will see an example for file operations: 

shankys:/home/user1:>cat fileperl.pl
#open file in apped mode
open (MYFILE, '>>test.txt');# test.txt is in current directory.
#adding some lines to the file
print MYFILE "A new line\n";
#opeing file for just reading.
open (MYFILE,"test.txt");
while (<MYFILE>)
#closing the file
close (MYFILE);


Creating and working with array of elements

To create an array of integers:


Lenght of array: $#array

To print contents of the arrat:

print @array;

Get an element of an array

var= @array[1];

or var= (1,3,4,5,6)[1], will give assign 2nd element i.e. 3 to var.

To pop the last element from the array 

var= pop (@array);

To push a new element to the array:

push(@array, 34); # 34 will be pushed into the array.

See this example wirh array operations:

server1:/home/user1:>cat arrayperl.pl
#declare an array

print ("\nFirst field:$var");
print ("\nSecond field:$var1\n");
#To print the entire array
print @b;
print "\nLength of array b:$#b";
foreach $elem(@a)
    print "\n";
    print $elem;

print "\nPopped element:$var";
push (@b,34);
print "\nEntire array after push:@b";