Joe’s Notes on Perl #2 – Lists, Arrays and Hashes

Last time I went though scalars and how to use operators. Today is arrays, hashes and lists.

As from last time all my variables will now be prefixed with my to help with debugging and general flow. The usefulness of my will become apparent when we explore loops.

Lists

Lists are quick ways of defining scalars.

This is essentially quicker than declaring $a = 1, $ a=2 etc.

Some functions for strings:

 

Arrays – @

Arrays are an ordered set of strings. These are very useful for calling known values.

To define an array use my @arrayname. To access a single element in an array use $arrayname[number]. All arrays are zero numbered so 0 is the start number. Perl will automatically switch between arrays and scalars as needed.

As you can see there is “More than one way to do it.” The top example @cats shows the more compact way, while @cats2 is a bit easier to read, you may choose to do whatever is the easiest for you.

The final lines above shows that you can create lists based on arrays. Declaring $a, $b and $c will implicitly call $cats[0], $cats[1] and $cats[2]. However, if an element doesn’t exist in an array it will be undefined.

The final line shows how Perl fills up lists from arrays. First it fills $e, $f and $g with the values in @cats. After that @h fills up with values from @cats2. This could be extended to catch values that you may not have expected however, that isn’t relevant now.

Functions for arrays and lists are the same as for strings.

Some examples of functions being used:

However there are Array based functions as well:

 

Hashes – %

Hashes can be thought of as an unordered set of data accessed by keys. Define a hash with %hashname and access elements in hashes by calling the “key” $hashname{key}. Keys must be unique. For example:

Whatever way you want to define a hash is fine but #2 is probably the easiest to read and type.

Hash functions work like array functions:

So there we have a quick run down on how hashes work.

Have fun!