More Perl


Arrays

 @days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
 @languages = qw(peaches apples pears);

Accessing Array Elements

 @days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
 $dayOfWeek = $days[1];

"Tuesday"


Taking a Slice of an Array

 @array[m, n, ...]
 @fruits = qw(lemons, peaches, oranges, apples, limes, bananas);
 @citrus = @fruits[0,2,4];	# these are equivalent ways ...
 @select = (0, 2, 4);
 @citrus = @fruits[@select];	# ... of specifying the slice

("lemons", "oranges", "limes")


List Assignment

 ($mon) = @days;
 ($mon, $tue) = @days;
 $lastDay = $days[-1];

Replacing Elements in an Array

 $fruits[4] = "pear";
 @fruits[0,2] = ("persimmon", "pommegranade");

Length of an Array

 $length = @days;
 $days
 $#days + 1;

Processing All Array Elements

 @numbers = (1 4 9 16 25);
 foreach $number (@numbers) {
	$number = sqrt($number);
 }

(1, 2, 3, 4, 5)


List Operators


Using Arrays as Queues

 @cds = ("Motherland", "Stunt", "Reckless");
 $first = shift(@cds);

"Motherland"

 unshift(@cds, "Zooropa");

("Zooropa", "Stunt", "Reckless")


Using Arrays as Stacks

 @list = ("h1", "table");
 push(@list, "tr");

("h1", "table", "tr")

 $last = pop(@list);

"tr"


Concatenating Arrays

 (@first, @second, ...)
 ((1, 2, 3), ('a', 'b'))

(1, 2, 3, 'a', 'b')


Splitting Strings into Parts

 $query = "user=foo&password=bar";
 @parameters = split /&/, $query;

('user=foo', 'password=bar')


Sorting Arrays

 sort @list;		# ascending alphabetical order
 sort {$b cmp $a} @list;	# descending alphabetical order
 sort {$a <=> $b} @list;	# ascending numerical order
 sort {$b <=> $a} @list;	# descending numerical order

Complete Example

 $index = 0;
 while ($name = <STDIN>) {
	chomp $name;
	$names[$index++] = uc($name);		# convert to uppercase
 }
 print "\nThe sorted list of names is:\n\n";
 foreach $name (sort @names) {
	print "$name\n";
 }

Hilda Betrand Sophie Michael

The sorted list of names is:

BETRAND HILDA MICHAEL SOPHIE


Hashes

 %phone = (
	Bob => '1234',
	Alice => '2345',
	Mary => '3456'
 );
 %phone = ('Bob', '1234', 'Alice', '2345', 'Mary', '3456');

Getting and Setting Hash Elements

 $query = $ENV{'QUERY_STRING'};
 @numbers = @phone{'Bob', 'Alice'};

('1234', '2345')

 $phone{'Bob'} = '8888';		# Bob's new phone number

Getting the Keys and Values

 @listings = keys %phone;

('Bob', 'Alice', 'Mary')

 foreach $key (keys %phone) {
	print "$key ... $phone{key}\n";
 }
 @numbers = values %phones;

('8888', '2345', '3456')


Accessing Keys and Values Simultaneously

 while (($key, $value) = each %phone) {
	print "<p>The phone number for $key is $value.\n";
 }

<p>The phone number for Bob is 8888. <p>The phone number for Alice is 2345. <p>The phone number for Mary is 3456.


Checking if a Hash Contains a Key

 $name = 'Joe';
 if (exists $phone{$name))  {
	print "The directory contains a listing for $name.";
 } else {
	print "No listing for $name."
 }

Removing Key-Value Pairs

 $value = delete $phone{'Mary'};

Complete Example

Bareneaked Ladies:Stunt:Warner:1998
Blue Rodeo:The Days in Between:2000 
Great Big Sea:Up:Warner:1995
Natalie Merchant:Motherland:Elektra:2001
Rheostatics:Night of the Shooting Star:Drog:2001
The Grapes of Wrath: Now and Again:Capitol:1989 
#!/usr/bin/perl

while () {
  chomp;
  $year = (split /:/)[3];
  $years{$year}++;
}
foreach (sort keys %years) {
  print "In $_, $years{$_} CDs were released.\n";
}
In 1989, 1 CDs were released.
In 1995, 1 CDs were released.
In 1998, 1 CDs were released.
In 2000, 1 CDs were released.
In 2001, 2 CDs were released.

References


References (Syntax)


Nested Data Structures


Accessing Elements


Accessing Elements (Syntactic Sugar)


Anonymous Arrays and Hashes


Anonymous Arrays and Hashes (Example)


Nested Data Structures (Again)


Nested Data Structures (Example)


Complete Example

Bareneaked Ladies:Stunt:Warner:1998
Blue Rodeo:The Days in Between:2000 
Great Big Sea:Up:Warner:1995
Natalie Merchant:Motherland:Elektra:2001
Rheostatics:Night of the Shooting Star:Drog:2001
The Grapes of Wrath: Now and Again:Capitol:1989 
#!/usr/bin/perl

# parse
@attrs = qw(artist title label year);
while () {
  chomp;
  my %rec;   # creates a new local variable, see section on
             # subroutines for a full discussion
  @rec{@attrs} = split /:/;
  push @cds, \%rec;
}

# munge
foreach (@cds) {
  $artists{$_->{artist}}++;
}

# output
foreach (sort keys %artists) {
  print "$_: $artists{$_}\n";
}