Perl Workshop
Perl Workshop
C. David Sherrill
Center for Computational Molecular
Science & Technology
Georgia Institute of Technology
References
• These notes follow the progression given
by the introductory book, “PERL in easy
steps,” by Mike McGrath (Computer Step,
Warwickshire, UK, 2004)
• Another good book is “Learning PERL,” by
Randal L. Schwartz, Tom Phoenix, and
Brian D. Foy (O’Reilly, 2005)
• See also www.perl.org and www.perl.com
Perl at a Glance
• High-level language
• Popular
• Easy to use for processing outputs
• Good for web CGI scripts
• Interpreted language --- not high-
performance
• Remember to make your scripts
executable (e.g., chmod u+x [scriptname])
Part 1: Variables and Printing
Printing in Perl
#!/usr/bin/perl
# initialize a string
$greeting = “hello”;
# initialize an integer
$number = 5;
# set up an array
@array = (“hi”, 42, “hello”, 99.9);
$length = @array;
print “There are $length elements in the array\n”;
Hash variables
• These contain key/value pairs and start with the % symbol, e.g., %h
#!/usr/bin/perl
%h = (“name”, “David”, “height”, 6.1, “degree”, “Ph.D.”);
$x = 3;
$y = 5;
$z = $x + $y;
print "$x + $y = $z\n";
#3+5=8
$z = ++$x + $y;
print "$x + $y = $z\n";
#4+5=9
$x = 3;
$x = 1; $y = 0;
# example of AND
$z = $x && $y;
print "$x && $y = $z\n";
# prints 1 && 0 = 0
# example of OR
$z = $x || $y;
print "$x || $y = $z\n";
# prints 1 || 0 = 1
# example of NOT
$z = !$y;
print "!$y = $z\n";
# prints !0 = 1
# example of NOT
$z = !$x;
print "!$x = $z\n";
# prints !1 = 0 ? No, actually it leaves $z as a blank!
Numerical comparison
Operator Comparison • < = > returns -1,
== Is equal? 0, or 1 if the left
side is less than,
!= Not equal? equal to, or
<=> Left-to-right comp greater than the
right side
> Greater?
• Other operators
< Less than? return TRUE if
>= Greater or equal? the comparison is
true, otherwise it
<= Less than or will be blank!
equal?
Numerical comparison example
#!/usr/bin/perl
$z = (2 != 3);
print "(2 != 3) = $z\n";
# prints (2 != 3) = 1
$z = (2 == 3);
print "(2 == 3) = $z\n";
# prints (2 == 3) =
String comparison
Operator Comparison/Action
eq is equal?
ne not equal?
gt greater than?
Lt less than?
cmp -1, 0, or 1, depending
. concatenation
x repeat
uc(string) convert to upper case
lc(string) convert to lower case
chr(num) get char for ASCII num
ord(char) get ASCII num of char
$a = "hi";
$b = "hello";
$equal = $a eq $b;
print "$a eq $b = $equal\n";
$equal = $a eq $a;
print "$a eq $a = $equal\n";
$equal = $a ne $b;
print "$a ne $b = $equal\n";
$a = "hi";
$b = "hello";
$c = $a . $b;
print "c = $c\n";
# prints "c = hihello"
$c = uc($a);
print "uc($a) = $c\n";
# prints "uc(hi) = HI"
$c = $a x 5;
print "$a x 5 = $c\n";
# prints "hi x 5 = hihihihihi"
The range operator
• The range operator, .., fills in a range of values
in between the endpoints
• @numbers = (1..10) gives @numbers = (1, 2, 3,
4, 5, 6, 7, 8, 9, 10)
• @letters = (“a”..”z”) gives an array with all letters
“a” through “z”
• A “for” statement can also use a range operator
to loop through a range, e.g.,
“for (1..10) { print “hi” };” would print “hi” 10 times
Math functions
• PERL has several built-in mathematical functions
Function Operation
#!/usr/bin/perl
$major = “chemistry”;
if ($major eq “chemistry”) {
print “Welcome, chemistry student!\n”;
}
if ($major ne “chemistry”) {
print “You’re not a chemistry student.\n”;
print “Why not?\n”;
}
# note: need the curly braces
IF/ELSE statements
• Sometimes more convenient than just “IF” statements
#!/usr/bin/perl
$major = "chemistry";
if ($major eq "chemistry") {
print "Welcome, chemistry student!\n";
}
else {
print "You're not a chemistry student.\n";
print "Why not?\n";
}
# note: need the curly braces
ELSIF statements
• “elsif” is read as “else if”. It’s an “else” that has an “if” condition attached to it; useful
in picking one possibility out of a list of several
#!/usr/bin/perl
$grade = "F";
if ($grade eq "A") {
print "Excellent!\n";
}
elsif ($grade eq "B") {
print "Good work.\n";
}
elsif ($grade eq "C") {
print "Needs improvement.\n";
}
else {
print "I suggest you start coming to office hours.\n";
}
FOR loop
• Loop (repeatedly execute a statement block) until a
given condition is met
• for (initializer, test, increment/decrement) {statement
block}
while ($i<3) {
print "i = $i\n";
$i++; # need this line to avoid infinite loop!
}
# prints the following:
#i=0
#i=1
#i=2
DO/WHILE loops
• Like “WHILE” but always executes at least once; test is made at end not
beginning of statement block
• There is a related “DO/UNTIL” loop
do {
print "i = $i\n";
$i++; # need this line to avoid infinite loop!
}
while ($i < 3);
# prints the following:
#i=0
#i=1
#i=2
NEXT statement
• Skip to next iteration of a loop
• Equivalent to C’s “continue” statement
print "@names1\n";
# prints David Daniel Justin
print "@names2\n";
# prints Mutasem Micah Arteum
print "$names1[1]\n";
# prints Daniel, *not* David!
print “$names1[-1]\n”;
# prints last element, Justin
Converting scalars to arrays
• Can take a scalar (like a text string) and
split it into components (like individual
words) and place them in an array
• Most frequently split using spaces or
commas
• Use the split() function
Scalars to arrays example
#!/usr/bin/perl
print "@words\n";
# prints "We are learning PERL"
print "$words[1]\n";
# prints "are"
$prime_list = "1,3,5,7,11";
@primes = split(/,/,$prime_list);
print "@primes\n";
# prints 1 3 5 7 11
Going through all elements
• “foreach” statement creates a loop that goes through all the elements in an
array
#!/usr/bin/perl
$i=0;
foreach $task(@tasks) {
print "Task $i: $task\n";
$i++;
}
unshift(@grades,54);
print "Grades are: @grades\n";
# Grades are: 54, 100, 90, 89
$deleted = shift(@grades);
print "Deleted the grade $deleted\n";
print "Grades are now: @grades\n";
# Deleted the grade 54
# Grades are now: 100, 90, 89
Other array tricks
• Combine two arrays like
@new = (@arr1, @arr2);
• Replace an individual element like
$arr[0] = 42;
• Get the length of an array like
$len = @array;
• Take a “slice” (subset) of an array
@subset = @arr[0,5];
• Get the reverse of an array
@rev = reverse(@arr);
Sorting
• Can sort the elements of an array alphabetically; will not change the original
array but can assign result to a new array. $a and $b are temp strings.
• Could do similar thing with numbers but using {$a Ù $b} for comparison
Part 5: Hashes
Hashes
• Key-value pairs; hash variables start with % symbol
• Very useful for keeping data from HTML forms
• Access a value by giving its associated key in curly
brackets; the accessed value is a scalar, not a hash, so
use $ in front
@names = @hash{"first","last"};
print "names: @names\n";
# names: David Sherrill
Getting all keys or all values
• Can get a list of all keys or all values in a hash using the keys() and
values() functions, which take the name of the hash as the argument
• Warning: the order of the keys/values is not necessarily the same as
the original ordering
@karr = keys(%hash);
print "keys: @karr\n";
# keys: first last job
@varr = values(%hash);
print "values: @varr\n";
# values: David Sherrill Professor
Looping through hash elements
• Can loop through the elements of a hash using the “foreach”
statement; like a “for” loop but goes through an array of elements
• Similar to “foreach” in shells like tcsh
• %hash = qw(first David last Sherrill job Professor);
foreach $i (keys(%hash))
{
# note: below we do $hash not %hash
print "The key is $i and the value is $hash{$i}\n";
}
delete $hash{"job"};
foreach $i (keys(%hash))
{
# note: below we do $hash not %hash
print "The key is $i and the value is $hash{$i}\n";
}
foreach $line(@lines)
{
print "$line";
}
sub pr_error
{
print "Received error on opening file.\n";
print "Error message: $_[0]\n";
exit;
}
Renaming and deleting files
• To rename a file
rename(“old_filename”, “new_filename”);
• To delete a file
(don’t use unless you’re sure!)
unlink(“file_to_delete”);
File status checks
Operator Operation
foreach $filename(@filenames)
{
print "$filename\n";
}
Selecting certain filenames
• Can use the grep() function, in conjunction with
a “regular expression” (see later), to select only
certain filenames
foreach $filename(@filenames)
{
print "$filename\n";
}
Setting permissions
• Can set the file permissions on a file or
directory using the chmod() function which
works like the UNIX command
sub pr_error
{
print "Error: $_[0]\n"; exit;
}
Making and deleting directories
• Make a directory (needs UNIX
permissions code)
mkdir(“subdir”, 0755);
• Delete a directory
rmdir(“subdir”);
• Best to check for errors, e.g.,
rmdir(“subdir”) || &pr_error($!);
Changing working directory
• The script usually assumes it is working in the
same directory it resides in
• This means files in other locations need to be
addressed with full or relative paths
• Instead, can tell PERL to use a different
“working” directory and then use “local”
filenames
• chdir(“../docs”); # go back up to the “docs”
directory and do all subsequent work in there