|
An array is a collection of scalar values. It's like a list of the people that you want to invite to a party. It's a rather silly (or nerdy, depending on your perspective) party so you refer to each guest by their position in your list rather than by their name. Operations like sorting in perl are quite simple to accomplish with lists. They can also be treated like other objects (if you're familiar with CSE 143's abstract data types, you might get excited about this) so operations like adding to them, or getting the first item are also easy (as opposed to languages like C++ where there is great pain involved in even the simplest array operation).
If I had a herd of camels and wanted to keep track of them, I might make a list of them. Since arrays are named with @ at the beginning, I would call the list @camel_herd. If I wanted to initialize, sort, and print it, it would look like this:
| Code | Result | Download |
#!/usr/local/bin/perl @camel_herd = ("black one","brown one","Freda","Cletus","gray one"); @camel_herd = sort @camel_herd; print @camel_herd;
|
CletusFredablack onebrown onegray one
|
 herd.pl
|
The parentheses are there to make sure nothing gets left off when assigning the list. Commas work just like in English to separate listed elements.
The output isn't particularly pretty, but that can be attributed to the fact that Perl's print statement needs a little bit more information about how to print an array than just it's name. The easiest way to do this is to surround the name with quotes, which forces the interpreter to place spaces between each of the values. The modified code is as follows:
| Code | Result | Download |
#!/usr/local/bin/perl @camel_herd = ("black one","brown one","Freda","Cletus","gray one"); @camel_herd = sort @camel_herd; print "@camel_herd";
|
Cletus Freda black one brown one gray one
|
 herd1.pl
|
If even that isn't enough satisfaction, the conversion from array to scalar gets a little more complicated. The join statement controls how an array is converted to a scalar. Since it's only useful in this case to print, it can feed it's results directly to print. The code to print each camel's name on a new line would look like this:
| Code | Result | Download |
#!/usr/local/bin/perl @camel_herd = ("black one","brown one","Freda","Cletus","gray one"); @camel_herd = sort @camel_herd; print join "\n",@camel_herd;
|
Cletus Freda black one brown one gray one
|
 herd2.pl
|
|