More hashes and sorting
Hash manipulation: each, delete, exists
Before we got side-tracked with subroutines and conditionals, we covered arrays in some detail, and saw the various functions, like push and pop that you can torture them with. The functions for torturing hashes are our next port of call. Perl stores the key => value pairs of a hash in essentially random order (well, unhelpful, if not actually random), so operations like pushing and popping don’t make any sense, as hash items are not ordered in a useful fashion. We’ve already seen how to extract single items and slices of hash:
Conditionals
Conditionals: if and unless
We’re on the home-straight in understanding the code from the last post now:
#!/usr/bin/perl
use strict;
use warnings;
my @peas = qw/chick mushy split/;
while ( my $type = pop @peas ) {
print "$type peas are ", flavour( $type ), ".\n";
}
sub flavour {
my $query = shift @_;
my @peas = qw/chick garbanzo/;
foreach ( @peas ) {
if ( $query eq $_ ) {
return "delicious";
}
}
return "disgusting";
}The very last bit is the conditional statement in the flavour() subroutine. This part compares the type of pea the subroutine was passed with all the peas in its own @peas, and if it matches any of them, the subroutine returns ‘delicious’. The if conditional has the general form:
Bondage, discipline and subroutines
Lexical my variables and use strict;
You may have noticed a little thing I slipped in the last script: the keyword my in the chomp. my is a very important keyword, although you’ll note that it doesn’t seem to make any difference if you delete it and run the program. What my does is pin a variable to a particular part of your program, so that it can’t be seen from elsewhere. This may not seem very useful at the moment, but is exceedingly important as your programs get bigger. Such as here:
Prettier loops and nicer code
Idiomatic Perl
The original code we were studying is very ugly, and Perl makes writing short, diabetogenic code easy. It also makes writing shoddy, abominable code easy too, but I wouldn’t recommend this as a course of action. A much more attractive way of writing the horrible code from the last page is:
#!/usr/bin/perl
print "What is your name?";
chomp( $name = <STDIN> );
@beans = qw( adzuki haricot mung );
print "\@beans contains ", scalar @beans, " members, @beans\n";
foreach ( @beans ) {
print "$name likes $_ beans.\n";
}This is much tidier, and probably more readable even without any further explanation. There are a few new things though. The assignment of <STDIN> ("Steve\n" or whatever) to $name actually returns the variable $name, which is exactly what chomp needs to work on. So those two lines can be combined:
Simple loops
Loops
Hopefully you’re now happy with the fundamental data types in Perl: scalars, arrays and hashes, so most of the script below shouldn’t be too mysterious:
#!/usr/bin/perl
print "What is your name?\n";
$name = <STDIN>;
chomp $name;
@beans = ( "adzuki", "haricot", "mung" );
print( "\@beans contains ", scalar @beans, " members: @beans\n" );
for ( $i = 0; $i < scalar @beans; $i++ ) {
print "$name likes $beans[$i] beans.\n";
}@beans contains 3 members: adzuki haricot mung
Steve likes adzuki beans.
Steve likes haricot beans.
Steve likes mung beans.Don’t get scared by the line-noise (i.e. all the punctuation): if you do, regexes will probably be fatal. The very beginning should be quite obvious now:
Hashes
Hashes
Perl actually has two sorts of array. Simple arrays like those we’ve already discussed are simply called arrays. The second sort of array is called an associative array, or hash. They’re very similar to dictionaries, if you’re a Python programmer. Hashes are created with a % for %we_ran_out_of_sensible_symbols, and contain pairs of data (ah, maybe it was for the two blobs in a % sign) called keys and values. Here are some typical hash creations:
Arrays and slices
Types
You should now be able to create very simple scripts that can take input from the keyboard, assign it to scalar variables, and echo it back to the screen with print. Time for some technicalities.
Perl is often (and wrongly!) termed a weakly typed language. For those of you coming from bondage and discipline languages like C or Java, this means Perl does not require you to explicitly point out what kind of variable your variables are: floats, doubles, integers, characters, booleans, strings, etc.
Input and output
Input
The “not a hello world script” script is a little dull. Let’s try something a more useful:
#!/usr/bin/perl
print "What is your name?\n";
$name = <STDIN>;
chomp( $name );
print "$name likes beans.\n";Don’t forget the semicolons at the end of each statement.
The first line of this program should be obvious now, but the others may need a little explaining. The second line contains the line-reading operator < > and the STDIN filehandle. STDIN (the “standard input filehandle”) is automatically opened whenever you run perl, and is where things inputted through pressing buttons on the keyboard live. If you surround a filehandle like STDIN with the < > line reading angle brackets, you will read a line from that filehandle. A line to perl is some text followed by a newline character, hence:
Not a hello world script
Rather than employing the usual tactic of showing you how to write the accursed ‘hello world’ program, so beloved of all computer programming introductions, let’s start with something entirely different:
print "This is most definitely not a hello world script.\n";If you save this as the file thing.pl, or similar, then you can run it from the command line (i.e. DOS prompt, bash shell, terminal window) thusly:
Educated guesswork
Someone recently asked me, “How many cells are there in the human body?”
I have quite a lot of correspondence of this kind, just to be clear.
I have to confess my first thought was “Not a bloody clue”. My second thought was “I bet the Internet knows”; but my third was “The Internet is full of bloody lies”.
My fourth thought went on for so long, it became part of the introduction to cell biology and genetics lecture I gave this year, and is reproduced below for your pleasure.
