Thursday, July 20, 2006
Perl Notes

Running Perl programs
To run a Perl program from the Unix command line:
#perl.pl Perl statements end in a semi-colon: print "Hello, world";
Double quotes or single quotes may be used around literal strings:
print "Hello, world"; print 'Hello, world'; However, only double quotes "interpolate" variables and special char- acters such as newlines ("\n"): You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence. print "Hello, $name\n"; # works fine print ’Hello, $name\n’; # prints $name\n literally
my $os1="Suse 10.1";
my $os2="Tiger 4.*.*.*";
my $no=13;
print"$os1 is far ahead than $os2\n";
print"Squar of $no is ",$no*$no,"\n";
O/P:
[root@station1 perl]# perl perl4.pl
Suse 10.1 is far ahead than Tiger 4.*.*.*
Squar of 13 is 169
my @number = (13,26,39);
print $number[0],"\n";
print $number[1],"\n";
print $number[2],"\n";
O/P:
13
26
39
EG:
my @lang = ("linux","mac","solaris","windows");
print $lang[0],"\n";
print $lang[1],"\n";
print $lang[2],"\n";
print $lang[3],"\n";
O/P:
linux
mac
solaris
windows
EG:
my @info=("Parag",63,"EN-4A");
print $info[0],"\n";
print $info[1],"\n";
print $info[2],"\n";
O/P:
Parag
63
EN-4A
The special variable $#array tells you the index of the last element of an array:
EG:
my @mixed = ("camel", 42, 1.23); print $mixed[$#mixed];
O/P:
[root@station1 perl]# perl perl8.pl
1.23
EG:
my @mixer = ("sam ",13,"mac ",26,"intel ","windows ");
print @mixer[0..5],"\n";
O/P:
[root@station1 perl]# perl perl9.pl
sam 13mac 26intel windows
if
if ( condition ) { ... } elsif ( other condition ) { ... } else { ... }There's also a negated version of it:
unless ( condition ) { ... } This is provided as a more readable version of if (!condition) .
Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like:
# the traditional way if ($zippy) { print "Yow!"; } # the Perlish post-condition way print "Yow!" if $zippy; print "We have no bananas" unless $bananas; while ( condition ) { ... } There's also a negated version, for the same reason we have unless :
until ( condition ) { ... } You can also use while in a post-condition:
print "LA LA LA\n" while 1; # loops forever
Exactly like C:
for ($i=0; $i <= $max; $i++) { ... } The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning foreach loop.
Perl operators are documented in full in perlop, but here are a few of the most common ones:
-
+ addition - subtraction * multiplication / division
-
== equality != inequality < less than > greater than <= less than or equal >= greater than or equal
-
eq equality ne inequality lt less than gt greater than le less than or equal ge greater than or equal
