The splice Function

The splice function allows you to remove or replace part of an array. The simplest form of this function looks like the following:

splice @array, $offset;

This deletes the elements in the array starting at offset and going to the end of the array.

For example:

my @array = (0, 1, 2, 3, 4, 5); 
splice(@array, 3); 
print "@array
";

This prints “0 1 2” (elements from 3 on removed). If the offset is negative, the number of elements is counted from the end of the array rather than the start. For example, if you apply the following to the original array

splice(@array, –2);

you get “0 1 2 3” (two elements dropped from the end).

The splice Function’s Return Value

The splice function returns different things depending on whether it’s used in the array context or the scalar context. Array context means that the result is assigned to an array, or the function is used in a place where you would expect an array. Similarly, a scalar context is where the result is assigned to a scalar or used as if it were a scalar.

When used in the array context, the splice function returns the elements deleted. For example:

my @array = (0, 1, 2, 3, 4, 5); 
my @result = splice(@array, 3);    # Array context 
print "@result
";

This prints the removed elements “3 4 5”.

In the scalar context, it returns the last element removed. For example:

my @array = (0, 1, 2, 3, 4, 5); 
my $result = splice(@array, 3);    # Array context 
print "$result
";

Because three elements were removed, this prints “5”.

Additional splice Arguments

By default, splice deletes all the elements from the offset to the end of the array. The splice function allows you to supply an additional argument, length, which tells splice how many elements to delete:

@new_array = splice @array, $offset, $length

For example:

my @array = (0, 1, 2, 3, 4, 5); 
splice(@array, 3, 2); 
print "@array
";

This example deletes two elements starting with the third element and prints “0 1 2 5”.

Finally, splice lets you supply a set of elements to be inserted into the array at offset :

@new_array = splice @array, $offset, $length, REPLACEMENTS

(REPLACEMENTS can be a list of scalars or an array expression.)

For example, replace one element of an array with a new value:

my @array = (0, 1, 2, 3, 4, 5); 
splice(@array, 3, 0, "sam", "joe", "mac"); 
print "@array
";

This command goes to element #3 (offset ), deletes one element (length), and inserts three new elements (“sam”, “joe”, and “mac”) before element #3. The result is

0 1 sam joe mac 4 5

This example uses three scalars as replacement elements. You could just as easily have used an array or array expression:

my @new_stuff = qw(sam joe max); 
splice(@array, 3, 0, @new_stuff);

Figure 3.2 illustrates how the various forms of splice work.

Figure 3.2. The splice function.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset