September 12, 2004 3:00 PM
Some notes about Perl1. Basically, stuff that I keep on having to re-learn every time I need to use perl after I get out of touch with it.

if, while, for, foreach, etc. all require curly braces even if there is only one statement in the block.

Subroutine definitions doesn't have any argument list. The arguments are inside an array @_. The first argument can be obtained via the variable $_[0]. Arguments can also be obtained via multiple calls to shift; which takes @_ as the default argument in a subroutine.

Any array that is passed as an argument loses it's identity. That is, the array holding the arguments is always a flat list. To gather the elements of the array, pass it via reference. This can be done via a backslash before the array name. To retrieve the array from the reference in a subroutine, use @{$_[0]}. Therefore, the first element is @{$_[0]}[0]. The changes made to this element will be reflected outside the function as well.

The last index of the array can be obtained from $#arr though using @arr in a scalar context automatically returns the number of elements in the array.

last is equivalent to break and next is equivalent to continue in C.

my keyword has to be present before the first occurrence of a variable if it is to have lexical scope. If omitted, recursive functions will go haywire. Interpreter can be told to check by using use strict; at the top of the perl script.

Regular expression match can be performed by if ($a ~ /regexp/). Replace can be done using $a ~ s/searchreg/replacetext/g. /g implies that all instances of searchreg to be replaced.

Here's a lame version of Quicksort implemented in perl:

sub partition {
    my $leftptr=$_[0]-1;
    my $rightptr=$_[1];
    my $key=$_[2];
    while (1)
	do {$leftptr++;}
	while($leftptr < $key);
	do {$rightptr--;}
	while ($rightptr > 0 && $rightptr > $key);
	if ($leftptr >= $rightptr)
	    my $temp = $arr[$leftptr];
	    $arr[$leftptr] = $arr[$rightptr];
    if ($leftptr != $_[1]) {
	$temp = $arr[$leftptr];
    return $leftptr;
sub qsort {
    my $left = shift;
    my $right = shift;
    if ($right - $left < 0)
    else {
	$part = partition($left,$right,$arr[$right]);   
    return @arr;
print "Enter an integer array (Cntrl + D to stop): ";
@arr = <stdin>;
print "Sorted Array:\n";
print @arr;


[1] Practical Extraction and Report Language.

Copyright © 2004-2011 Anirudh Sasikumar. All rights reserved.
Last Updated: January 21, 2005 4:27 PM