Perl logo

Perl Refreshments ⌘

Arrays #8 - Slice & Dice

We now know how to create arrays, sort them, and how to add or delete elements from an array. But there are times when you want only specific or certain items. How to do that?

This is where we need an array slicer. Wait, we already have one.

An array slice is just that - a selection of items from an array which now acts like a list.

Using our previous @foo (without the duplicates) example let's see if we can slice it up into something else ...

my @foo=(
    "toronto",
    "windsor",
    "hamilton",
    "london",
    "ottawa",
    "quebec",
    "sudbury",
    "timmins",
    "perth",
    "ancaster",
    "orillia",
);

For some reason we only want the odd numbered elements. Here's how we do that:

my @foo=(
    "toronto",
    "windsor",
    "hamilton",
    "london",
    "ottawa",
    "quebec",
    "sudbury",
    "timmins",
    "perth",
    "ancaster",
    "orillia",
);
my @odds = @foo[1,3,5,7,9];
print join(";",@odds) . "\n";

windsor;london;quebec;timmins;ancaster

Remember that arrays begin indexing at 0, so item #1 is 'windsor' not 'toronto'.

Let's try another ...

my @vowels=@foo[4,9,10];
print qq{\@vowels: } . join("|",@vowels) . "\n";

@vowels: ottawa|ancaster|orillia

Yes, we printed cities beginning with a vowel, but notice we have included a print and a join command in a single statement!

After slicing comes Splicing


-30-