Perl Scripting 3

Arrays and Hashes

Lincoln Stein

Genome Informatics

Suggested Reading

Chapters 3 and 5 in Learning Perl.

Lecture Notes -- Arrays

An Array Is a List of Values

For example a list with the number 3.14 as the first element, the string 'abA' as the second element, and the number 65065 as the third element.

"Literal Representation"

We write the list as above as
(3.14, 'abA', 65065)
If $pi = 3.14 and $s = 'abA' we can also write
($pi, $s, 65065)
We can also do integer ranges:
(-1..5) 
shorthand for
(-1, 0, 1, 2, 3, 4, 5) 
Counting down not allowed!

Array Variables and Assignment

my $x = 65065;
my @x = ($pi, 'abA', $x);
my @y = (-1..5);
my @z = ($x, $pi, @x, @y);
my ($first, @rest) = @z;

Getting at Array Elements

$z[0]      # 65065
$z[0] = 2;
$z[0]      # 2
$z[$#z];   # 5
Skip "slices" for now.

Push, Pop, Shift, Unshift

Add 9 to the end of @z;
push @z, 9;
Take the 9 off the end of @z, and then take the 5 off the end:
my $end1 = pop @z;
my $end2 = pop @z;
Add 9 to the beginning of @z;
unshift @z, 9;
Take the 9 off the beginning of @z, and then take the 3.14 off the beginning:
my $b1 = shift @z;
my $b2 = shift @z;

Reverse

my @zr = reverse @z;

Sorting

Alphabetically:
my @zs = sort @z;
Numerically:
my @q = sort { $a <=> $b } (-1, 3, -20)

Split and Join

my @q = split /\d+/, 'abd1234deff0exx'
# ('abd', 'deff', 'exx');

Swallowing Whole Files in a Single Gulp

my @i = <>;
chomp @i;

Array and Scalar Context

The notion of array and scalar context is unique to perl. Usually you can remain unaware of it, but it comes up in reverse, and can be used to get the size of an array.
print reverse 'ab'; # prints ab!!! (reverse in array context)
$ba = reverse 'ab'; # $ba contains 'ba' (reverse in scalar context)
print scalar reverse 'ab'; # prints ba
print scalar @z; # print the size of @z

Lecture Notes -- Hashes

A Hash Is a Lookup Table

A hash is a lookup table. We use a key to find an associated value.
my %translate;
$translate{'atg'} = 'M';
$translate{'taa'} = '*';
$translate{'ctt'} = 'K';  # oops
$translate{'ctt'} = 'L';  # fixed
print $translate{'atg'};

Getting All Keys

keys %translate

Removing Key, Value Pairs

delete $translate{'taa'};
keys %translate;

Initializing From a List

%translate = ( 'atg' => 'M',
               'taa' => '*',
               'ctt' => 'L',
               'cct' => 'P', );

Workshop Problem Set

Problem #1

Exercises 1-3, page 55, Learning Perl.

Problem #2

Exercises 1, page 84, Learning Perl.

How the program (call it mapper.pl in exercise 1 works:

$ mapper.pl red
apple
$ mapper.pl green
leaves
$ mapper.pl blue
ocean

Genome Informatics


Lincoln Stein lstein@cshl.org
Last modified: Mon Oct 18 14:50:33 EDT 2004