Perl Scripting

Input

Stdin

To read from STDIN use @array = <STDIN> and the @array now contains everything from STDIN.

Arguments

To take arguments, use @ARGS, as the array of arguments (you can them open the files).

Files

Open all Args as Files or read from Stdin

To open all arguments as files, and if none read from STDIN do the following:

while (<>) {
    print $_;
}

Open Files

We can open files as the following:

open(names,"<$files[0]") or die "$0: Can't open $files[0]: $!\n";

The "<" in front of "$files[0]" means we open it for read only. ">" means for writing, and "»" means appending.

Reading Files Into Strings

Files can easily be read into strings rather than into a \n separated array:

use File::Slurp
$string = read_file("blah.txt");

Arrays

Arrays in Perl are quite simple.

  • Each element is accessed with $array[0]
  • They're declared with @array = ("element1", "element2") etc
  • Allocating a variable to be an array doesn't allocate the first or last element of it, it allocates to it the length.

e.g.

$numItems = @array;
$numItems = $#array+1

Shift

Shift moves all elements of the array one to the left, whilst dropping the first one out (and assigning it to a variable if specified).

e.g.

$n_lines = shift @ARGV;

Printing Arrays

Arrays in perl print differently if you surround them with quotes.

@a = (1..5);
print @a;
# prints 12345
print "@a";
# prints 1 2 3 4 5

$0

$2 or $1 or $anynumber in Perl is not a reference to arguments, like in shell scripting, but is used in sed replacement to allow grouping to occur.

e.g.

$i =~ s/hello (world)/goodbye $1/

$_ and @_

$_ in perl is set to be the variable used if one isn't specified.

E.g.

@array = ("Hello","Goodbye");
 
foreach (@array) {
   print ;
}

is equivalent to

@array = ("Hello","Goodbye");
 
foreach $i (@array) {
   print $i;
}

@_ is the default variable for the list of arguments passed into a subfunction (so $_[0] is the first argument).

Command Switches

Command Switches are used to modify the way perl Runs.

  • -n or -p create an implicit while (<>) loop

Strings

Chomp

Takes off leading and trailing whitespace of a string. Uses $_ if not given an argument

Split

Splits a string into different cells of an array. Can split based on regex.

E.g.

$_ = "Capes:Geoff::Shot putter:::Big Avenue";
@personal = split(/:+/);
 
is the same as
 
@personal = ("Capes", "Geoff",
             "Shot putter", "Big Avenue");

Dereferencing

Perl dereferences strings if you put a $ in front of it.

$foo = 42;
$bar = "foo";
print "$$bar"; 
#prints 42

Functions (Subroutines)

sub add {
   ($num1, $num2) = @_;
   return ($num1 + $num2);
}
 
$result = &add($x, $y);