Perl logo

Perl Refreshments ⌘

Arrays #9 - Splice

No this is not a joke. We can slice and splice arrays (amongst other things).

Splicing is when you want to join one thing to itself or something else, like splicing one rope to another.

Splicing with arrays is used when you want to add some items of one array into another array.

splice REMOVES elements designated by OFFSET and LIMIT below, and replaces them with LIST if any.

Formally here is the syntax:

splice (ARRAY, OFFSET, LENGTH, LIST)
splice (ARRAY, OFFSET, LENGTH)
splice (ARRAY, OFFSET)

As you can see this seems to be a very powerful tool, and as with many tools, it must be used with caution.

Sticking with our cities example, let's see what we can do. First we'll start with an array of some Ontario cities (because I live in Ontario). Then we'll make another array of Québec cities.

my @on=(
	"Toronto",
	"Windsor",
	"Hamilton",
	"London",
	"Ottawa",
	"Sudbury",
	"Timmins",
	"Perth",
);
print qq{\@on:\n} . join("\n",@on) . "\n\n";

@on:
Toronto
Windsor
Hamilton
London
Ottawa
Sudbury
Timmins
Perth

my @pq=(
	"Montreal",
	"Kipawa",
	"Val d'Or",
	"Québec",
	"Chicoutimi",
	"Gaspé",
	"Ivujivik",
	"Matagami",
);
print qq{\@pq:\n} . join("\n",@pq) . "\n\n";

@pq:
Montreal
Kipawa
Val d'Or
Québec
Chicoutimi
Gaspé
Ivujivik
Matagami

Now we will splice the Québec array into the Ontario array beginning at index #2 ...

splice (@on,2,1,@pq);
print qq{\@on\n} . join("|",@on) . "\n\n";

@on
Toronto|Windsor|Montreal|Kipawa|Val d'Or|Québec|Chicoutimi|Gaspé|Ivujivik|Matagami|London|Ottawa|Sudbury|Timmins|Perth

Notice that ONLY @on[2] (Hamilton) has disappeared and been replaced by all of @pq, then the rest of @on.

This is a result of the 2,1 constraint in the splice command.


-30-