Home
 

Perl

Presentation by Ronald Blaschke (11/19/1999)

Background

  • First Release in 1987 by Larry Wall
  • Usefull for small and middle size projects
  • Great for text processing
  • Free available as source or precompiled binary for many platforms
  • Start your journey at http://www.perl.com/
  • Win32 version available from ActiveState
  • Lots of modules available through CPAN

The Language

  • Variables need not to be declared
  • Type of a variable is specified by prefix
  • 3 basic data types
    Scalar $var
    A single value, eg a string or number
    Array @var; $var[0] returns 1st element
    A array of scalars
    Associative Array/Hash %var; $var{$key} returns element with key $key
    A hash of scalars
  • Use of special variables for control information and default parameters
  • Subroutines receive their parameters via the special variable @_
  • Sophisticated Regular Expression Library

Examples

Example 1: Usage of variables

Illustrates the use of scalar/array/hash variables.

# <-- comments start with the hash sign

$text = "some text";
$num = 11;

## the following statements are true
## note: the == operator works on numbers, the eq operator on strings
($num == 11);
($text eq "some text");

## operations on numbers and strings
$num2 = $num+2;
$text2 = $text . " and some more text";

## again, these are true
($num2 == 13);
($text2 eq "some text and some more text");

## note that auto conversion between number and string takes place as needed
$text3 = $text . $num;
($text3 eq "some text11");

## an array can hold any scalar
@array = (1, 2, 4, "x");
($array[1] == 2);

## same for hash
%hash = ('key1' => 15, 'key2' => "text");
($hash{'key2'} eq "text");

Example 2: Hello World!

Prints nothing but... well, you know what.

The '#!/usr/local/bin/perl' tells the (UNIX) OS kernel to use an alternative shell. Note that the parenthesis may be omitted when calling a function.

#!/usr/local/bin/perl

print "Hello World!\n";

Sample Run

>./hello_world.pl
Hello World!

Example 3: Subroutines

Declares and calls a subroutine.

Note that no function parameters are declared; they are just thrown into the special variable @_. join simply joins together the elements of an array with the string as separator.

#!/usr/local/bin/perl

sub f1
{
    print "Sub args are: ", join(', ', @_), "\n";
}

f1(1, 2, 3, "x");

Sample Run

>./sub.pl
Sub args are: 1, 2, 3, x

Example 4: File Handling

Read a file, substitute something and write output.

The '<' or '>' in front of filename opens the file for reading or writing, respectively. A filehandle in angle brackets returns the next line of the file, or the undef value after the last one. The s/// operator performs a pattern substitution, the =~ operator binds the left scalar expression to the pattern. Note that there is no comma between the filehandle to write to (OUT) and the array to write ("$line").

#!/usr/local/bin/perl

open(IN, "< files.in");
open(OUT, "> files.out");

while(defined($line = <IN>)) {
    $line =~ s/foo/bar/g;
    print OUT $line;
}

close(OUT);
close(IN);

Sample Run

>cat files.in
This *foobar* will become a barbar!

>./files.pl

>cat files.out
This *barbar* will become a barbar!

Example 4: System Commands

Executes 'who' and extracts data from the result.

The backtick `` operator executes the enclosed system command and returns its output. split splits a string at the specified pattern up to a specified maximum. Note that ($var, $var, ...) is evaluated as an array, and a variable is specified by its name AND type. Therefore using $who and @who is ok. The pattern ' +' means 'at least one space.' Also remember that strings in double quotes are interpolated (ie variables and special characters are substituted), but in single quotes not.

#!/usr/local/bin/perl

@who = `who`;

foreach $who (@who) {
    ($login, $console, $month, $day, $time, $comments) = split / +/, $who, 6;
    print "$login: $console\n";
}

Sample Run

>who
jamie      pts/0        Nov 13 08:13    (chip.cs.bgsu.edu)
jbarnes    pts/1        Nov 12 09:05    (amnesia2.cs.bgsu.edu)
rblasch    pts/3        Nov 13 11:50    (tech139.labs.bgsu.edu)

>./exec.pl
jamie: pts/0
jbarnes: pts/1
rblasch: pts/3

Example 5: Dynamic Evaluation

Stores code in a variable and executes it as needed.

$code is executed as if the code is actual at this position. The string need not to be static; for example may come from a template file, user input, etc.

#!/usr/local/bin/perl

$code = '$b = 2 * $a';

$a = 15;
eval $code;
print "2 * $a is $b\n";

Sample Run

>./eval.pl
2 * 15 is 30

References