#!/usr/local/bin/perl # 1
@friends=("Pat","Chris","Jean"); # 2
$counter=0;while ($counter <= 2) # 3
{print "My favorite friend today is $friends[$counter]\n";$counter++;} # 4
The first thing you'll probably notice is the @. @friends is an array. It is actually a collection of values held under one name. The easiest way to refer to these values individually is by number. Line 2 could also have been broken up into three statements like this:
$friends[0]="Pat"; $friends[1]="Chris"; $friends[2]="Jean";
Notice how, true to binary ways, the first element of the array is at number 0. Also notice that when refering to a single element of an array, the array name is preceeded by a $ rather than the @ (it's $friends[0] not @friends[0])
We can put the power of arrays to use by using repeat loops. Using a while command with the $counter variable (line 3), we can do calculations on the array elements one at a time.
In line four, we are simply printing a line which includes a particular element of the array. For example, on the first time through the loop, $counter is 0:
$friends[$counter] ---> $friends[0] ---> "Pat"Notice the \n. It's a newline character (like a carriage return) which keeps the lines from running together. They must be in quotes, and Perl doesn't put them in for you.
After we print out one line, we add one to $counter ($counter++;) and go through the loop again with the next element of @friends.
And some more:
#!/usr/local/bin/perl #1
%title=("Bill","Mr. ",
"Manners","Miss ",
"Kirk","Captain ");
@people=("Kirk","Bill","Manners"); #5
foreach $person (@people)
{print $title{$person}.$person."rocks!";}
Ok, we've got 3 new things here:
Note that although I put each key/value pair on a seperate line, since Perl doesn't care about whitespace, they can be right next to each other. Just remember that it goes (key, value, key, value,...).
If not, you might want to back up and go a little slower.