Search This Blog

Thursday, February 26, 2009

A simple perl script variables, array, input, output and Reading a file in PERL

#!/usr/bin/perl
#
#output
print "********************\n";
print "First progarm in perl\n";
print "********************\n";

#variables
$var = "vikas";
print "\n$var\n";
$a=9;
$c=10;
$z=$a+$c;
print "\n$z\n";

#array
@nos = (1, 2, 3, 4, 5, 6);
push(@nos, 7);
print "\n@nos\n";
print @nos;
print "\n$nos[5]\n";

#inserting into array
push(@nos, 7);
print "\n@nos[6]\n";

#deleting from array
$arr=pop(@nos);
print "\nPoped -- $arr\n";

# length of array $#nos+1
$len = @nos;
print "\nlength -- $len and $#nos\n";
#array as string
$str = "@nos";
print "\narray as string -- $str\n";

#array
($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;
($a, $b) = @nos; # $a and $b are the first two
# items of @nos.
($a, @oth) = @nos; # $a is the first item of @nos
# @oth is a list of the
# others.
(@oth, $a) = @nos; # @oth is @nos and
# $a is undefined.

#reading from terminal
# total numbers of command line args = $#ARGV + 1
# here is first command lin argument
print "\n $ARGV[0]\n";
print "\n $ARGV[1]\n";

# reading all arguments using for loop
foreach $args (0 .. $#ARGV) {
print "$ARGV[$args]\n";
}

#input from terminal
print "\nEnter var 1 ";
$s = ;
print "\nEnter var 2 ";
$r = ;
#trimmming the input
chomp $r;
chomp $s;
#printing the input
print "----$r----$s------\n";


#File handling

$file = '/root/Desktop/ist.pl'; # Name the file
open(INFO, $file); # Open the file
@lines = ; # Read it into an array
close(INFO); # Close the file
print @lines;


#printing multiple lines
print <<"END";
#####################
vikas
sharma
coral

END

No comments:

Post a Comment