Perl literacy course.

Perl literacy course.

There's more than one way to do it

lecture #2

Shlomo Yona yona@cs.technion.ac.il http://yeda.cs.technion.ac.il/~yona/


Today

Today

  1. Grades average example
  2. Perl data structures
  3. subroutines
  4. very gentle introduction to perl regular expressions

Today's lecture will cover a lot of small details. We will run through many examples. Instead of trying to remember all the small details, try to focus on the big picture, as you can always check out the details on the freely available perldocs.


Calculating grades averages

Calculating grades averages

Given a list of grades for students, print the grades of each student along with an average.


Grades input file "grades"

Grades input file "grades"


barbara	62
barbara	14
barbara	66
dror	39
dror	47
amnon	81
barbara	60
barbara	17
barbara	76
amnon	20
amnon	31
amnon	34
barbara	89
barbara	10
dror	16
dror	37
dror	40
amnon	78
barbara	91
dror	26


output

output


amnon: 81 20 31 34 78    Average: 48.8
dror: 39 47 16 37 40 26       Average: 34.1666666666667
barbara: 62 14 66 60 17 76 89 10 91        Average: 53.8888888888889


The Perl code

The Perl code


#!/usr/bin/perl -w

$filename = "grades"; open(GRADES, $filename) or die "Can't open $filename: $!\n"; while ($line = <GRADES>) { ($student,$grade) = split(/\s+/, $line); $grades{$student} .= $grade . " "; }

foreach $student (sort keys %grades) { $scores = 0; $total = 0; @grades = split(" ", $grades{$student}); foreach $grade (@grades) { $total += $grade; ++$scores; } $average = $total / $scores; print "$student: $grades{$student}\tAverage: $average\n"; }


Functions and Statements

Functions and Statements

Perl has a rich library of functions. They're the verbs of Perl, the commands that the interpreter runs. You can see a list of all the built-in functions on the perlfunc main page. Almost all functions can be given a list of parameters, which are separated by commas.


Functions and Statements (cont.)

Functions and Statements

The print function is one of the most frequently used parts of Perl. You use it to display things on the screen or to send information to a file. It takes a list of things to output as its parameters.


print "This is a single statement.";
print "Look, ", "a ", "list!";


Functions and Statements (cont.)

Functions and Statements

A Perl program consists of statements, each of which ends with a semicolon. Statements don't need to be on separate lines; there may be multiple statements on one line or a single statement can be split across multiple lines.


print "This is "; print "two statements.\n"; print "But this ",
             "is only one statement.\n";


Perl's data structures

Perl's data structures

Yesterday we talked about scalars (which can contain numbers or strings).

Now we will get to know arrays and lists.


Arrays

Arrays

Arrays are an ordered set of scalars.

Array names begin with @.

You define arrays by listing their contents in parentheses, separated by commas:


@lotto_numbers = (1, 2, 3, 4, 5, 6);  # Hey, it could happen.
    @months = ("July", "August", "September");


Arrays (cont.)

Arrays

The contents of an array are indexed beginning with 0. (Why not 1? Because. Think of the indices as offsets, that is, the coun of how many array elements come before it. Obviously, the first element in the array has 0 elements before it.)


Arrays (cont.)

Arrays

To retrieve the elements of an array, you replace the @ sign with a $ sign, and follow that with the index position of the element you want. (It begins with a dollar sign because you're getting a scalar value.) You can also modify it in place, just like any other scalar.


@months = ("July", "August", "September");
print $months[0];   # This prints "July".
$months[2] = "Smarch";  # We just renamed September!


Arrays (cont.)

Arrays

If an array doesn't exist, it will be created when you try to assign a value to one of its elements.


$winter_months[0] = "December";  # This implicitly creates @winter_months.

The reason we use the $ sign and not the @ sign is because the value is a scalar value.


Arrays (cont.)

Arrays

The length of an array is given by using the array in scalar context:


@array = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
$num_elements = @array;	# 12
$last_index = $#array; # 11 (remember? arrays begin with the index 0)


Hashes

Hashes

Hashes are unordered sets of key-value pairs of scalars.

Each key in a hash has one and only one corresponding value.

The name of a hash begins with a percentage sign, like %parents.

You define hashes by comma-separated pairs of key and value, like so:


%last_day_in_month = ( "July" => 31, "August" => 31, "September" => 30 );


Hashes (cont.)

Hashes

You can fetch any value from a hash by referring to $hashname{key}, or modify it in place just like any other scalar.


print $days_in_month{"September"}; # 30, of course.
$days_in_month{"February"} = 29;   # It's a leap year.


Hashes (cont.)

Hashes

If you want to see what keys are in a hash, you can use the keys function with the name of the hash. This returns a list containing all of the keys in the hash. The list isn't always in the same order.


@month_list = keys %last_day_in_month;


Namespaces

Namespaces

The three types of variables have three separate namespaces.

That means that $abacus and @abacus are two different variables, and $abacus[0] (the first element of @abacus) is not the same as $abacus{0} (the value in the hash abacus that has the key 0).


Subs

Subs

So far, our Perl programs have been a bunch of statements in series. This is OK if you're writing very small programs, but as your needs grow, you'll find it's limiting.

A sub is defined with the sub keyword, and adds a new function to your program's capabilities. When you want to use this new function, you call it by name. For instance, here's a short definition of a sub called boo:


sub boo {
	print "Boo!\n";
}

boo(); # Eek!


Subs (cont.)

Subs

Whenever you call a sub, any parameters you pass to it are placed in the special array @_.

One value (either a scalar, an array or a hash) can be returned using the return keyword.


sub multiply {
	my @ops = @_;
	return $ops[0] * $ops[1];
}

for $i (1 .. 10) { print "$i squared is ", multiply($i, $i), "\n"; }


Subs (cont.)

Subs

Why did we use the my keyword? That indicates that the variables are private to that sub, so that any existing value for the @ops array we're using elsewhere in our program won't get overwritten.

You can also use my to set up local variables in a sub without assigning them values right away. This can be useful for loop indexes or temporary variables:


sub annoy {
	my ($i, $j);
	for $i (1 .. 100) {
		$j .= "Is this annoying yet?\n";
	}
	print $j;
}


Subs (cont.)

Subs

If you don't expressly use the return statement, the sub returns the result of the last statement. This implicit return value can sometimes be useful, but it does reduce your program's readability. Remember that you'll read your code many more times than you write it!


Very gentle introduction to regular expressions

Very gentle introduction to regular expressions

The simplest regex is simply a word, or more generally, a string of characters. A regex consisting of a word matches any string that contains that word:


"Hello World" =~ /World/;  # matches

In this statement, "World" is a regex and the "//" enclos­ ing "/World/" tells perl to search a string for a match. The operator "=~" associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, "World" matches the second word in ""Hello World"", so the expres­ sion is true. This idea has several variations.


Very gentle introduction to regular expressions (cont.)

Very gentle introduction to regular expressions

Expressions like this are useful in conditionals:


print "It matches\n" if "Hello World" =~ /World/;


reversing the sense of the match

reversing the sense of the match

The sense of the match can be reversed by using "!~" operator:


print "It doesn't match\n" if "Hello World" !~ /World/;


Using variables in a match

Using variables in a match

The literal string in the regex can be replaced by a variable:


$greeting = "World";
print "It matches\n" if "Hello World" =~ /$greeting/;

If you're matching against "$_", the "$_ =~" part can be omitted:


$_ = "Hello World";
print "It matches\n" if /World/;


match delimiters

match delimiters

The "//" default delimiters for a match can be changed to arbitrary delimiters by putting an "'m'" out front:


"Hello World" =~ m!World!;   # matches, delimited by '!'
"Hello World" =~ m{World};   # matches, note the matching '{}'
"/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin', 
			     # '/' becomes an ordinary char


order in a match

order in a match

Regexes must match a part of the string exactly in order for the statement to be true:


"Hello World" =~ /world/;  # doesn't match, case sensitive
"Hello World" =~ /o W/;    # matches, ' ' is an ordinary char
"Hello World" =~ /World /; # doesn't match, no ' ' at end


metacharacters

metacharacters

perl will always match at the earliest possible point in the string:


"Hello World" =~ /o/;       # matches 'o' in 'Hello'
"That hat is red" =~ /hat/; # matches 'hat' in 'That'

Not all characters can be used 'as is' in a match. Some characters, called metacharacters, are reserved for use in regex notation. The metacharacters are


{}[]()^$.|*+?\


metacharacters (cont.)

metacharacters

A metacharacter can be matched by putting a backslash before it:


"2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
"2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +
'C:\WIN32' =~ /C:\\WIN/;                       # matches
"/usr/local/bin/perl" =~ /\/usr\/local\/bin\/perl/;  # matches

In the last regex, the forward slash "'/'" is also backslashed, because it is used to delimit the regex.


metacharacters (cont.)

metacharacters

Non-printable ASCII characters are represented by escape sequences.

Common examples are "\t" for a tab, "\n" for a newline, and "\r" for a carriage return. Arbitrary bytes are represented by octal escape sequences, e.g., "\033", or hexadecimal escape sequences, e.g., "\x1B":


"1000\t2000" =~ m(0\t2)        # matches
"cat"        =~ /\143\x61\x74/ # matches, but a weird way to spell cat


interpolation

interpolation

Regexes are treated mostly as double quoted strings, so variable interpolation works:


$foo = 'house';
'cathouse' =~ /cat$foo/;   # matches
'housecat' =~ /${foo}cat/; # matches


anchors

anchors

With all of the regexes above, if the regex matched anywhere in the string, it was considered a match. To specify where it should match, we would use the anchor metacharacters "^" and "$". The anchor "^" means match at the beginning of the string and the anchor "$" means match at the end of the string, or before a newline at the end of the string.

Some examples:


"housekeeper" =~ /keeper/;         # matches
"housekeeper" =~ /^keeper/;        # doesn't match
"housekeeper" =~ /keeper$/;        # matches
"housekeeper\n" =~ /keeper$/;      # matches
"housekeeper" =~ /^housekeeper$/;  # matches


using character classes

using character classes


           /cat/;            # matches 'cat'
           /[bcr]at/;        # matches 'bat', 'cat', or 'rat'
           "abc" =~ /[cab]/; # matches 'a'


using character classes (cont.)

using character classes


/[yY][eE][sS]/; # match 'yes' in a case-insensitive way # 'yes', 'Yes', 'YES', etc. /yes/i; # also match 'yes' in a case-insensitive way


using character classes (cont.)

using character classes


/[\]c]def/; # matches ']def' or 'cdef'
$x = 'bcr';
/[$x]at/;   # matches 'bat, 'cat', or 'rat'
/[\$x]at/;  # matches '$at' or 'xat'
/[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'

The special character "'-'" acts as a range operator within character classes, so that the unwieldy "[0123456789]" and "[abc...xyz]" become the svelte "[0-9]" and "[a-z]":


/item[0-9]/;  # matches 'item0' or ... or 'item9'
/[0-9a-fA-F]/;  # matches a hexadecimal digit

If "'-'" is the first or last character in a character class, it is treated as an ordinary character.


using character classes (cont.)

using character classes


/[^a]at/;  # doesn't match 'aat' or 'at', but matches
      # all other 'bat', 'cat, '0at', '%at', etc.
/[^0-9]/;  # matches a non-numeric character
/[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary


character classes abbreviations

character classes abbreviations