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:
while (<FILEHANDLER>)
{print;}
To Close a file :
close (MYFILE);
So now, we will see an example for file operations:
shankys:/home/user1:>cat fileperl.pl
#!/usr/bin/perl
#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>)
{
print;
}
#closing the file
close (MYFILE);
Creating and working with array of elements
To create an array of integers:
@array=(1,2,3,4,5);
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
#!/usr/bin/perl
#declare an array
@a=(1,2,3);$var=(34,65,76)[0];
print ("\nFirst field:$var");
$var1=(34,65,76)[1];
print ("\nSecond field:$var1\n");
@b=(1,2,3,4,5);
#To print the entire array
print @b;
print "\nLength of array b:$#b";
foreach $elem(@a)
{
print "\n";
print $elem;
}
$var=pop(@b);
print "\nPopped element:$var";
push (@b,34);
print "\nEntire array after push:@b";