Programs and Statements

Perl programs begin with the “shebang” line which defines the location of the interpreter to use for this script. This seperates Perl programs from Python, Tcl, Bash, Awk, and other scriping languages

#!/usr/bin/perl -w
use strict 'refs', 'vars'; # Prevents us from making legal mistakes
use Carp; # loads the Carp (or other )module.
my ($arg1, $arg2) = @ARGV; # Access command line arguments
# The # indictates a comment until the end of the line
##############################################################
### Do program things
##############################################################
exit 1; # Sets the shell return code variable ($?) to this number.

Statements...

 
## Simple Statements ##
$v = expression; # Assignment
subname parameters; # invoke routine
subname(parameters); # alternate
 
## Conditionals ##
if (condition) { statements } # if true
elsif (condition { statements } # Optional
else { statements } # Optional
 
unless (condition) { statements } # if false
 
print $a if condition; # single-statement if
print $a unless condition; # single-statement unless
 
## Looping ## 
while (condition) { statements } # Loops while true
 
foreach $var (array) { statements } # Loops over array
 
for (start; condition, change) { statements } # standard for loop
for ($i=0; $i<=10; $i++) { print $i; } # prints 1..10
 
## Subroutines
 
sub subname { statements } # define
...
subname(parameters); # call
 
sub mysub
{
  my ($parm1, $parm2, $parm3) = @_; # get parms from perl's @_ array var
  return $parm2 || $parm2 || $parm3; # returns first true value
}
...
$result = mysub(0,'',3); # Should return 3
 
programming/perl/control.txt · Last modified: 2005/07/18 17:12 by allen