Sunday 29 December 2013

Splice function in Perl

While using arrays in a Perl program, sometimes you might require only a part or a chunk of the array instead of the whole.

Splice is a function which is used to carve an array and cut a portion out of it.

Consider the following illustration.

Eg:

@arr = ('10', '90', '30', '70', '40', '60');

Now as you may be aware, each value in the array is identified by it's index. The first element of the array is denoted by index 0. The second element is denoted by index 1 and so on...

Let's use the splice function to cut the array:

$portion = splice(@arr, 2, 4);

If you observe above, we have basically specified the range of elements from 2nd to 4th index within the array.

In this case the element on 2nd index from left is 30 (since foremost element's 10's index is 0) and the element on 4th index is 40)

The above command will result into values ('30', '70', '40') getting stored in the @portion array, which is a chunk of the original @arr array.

In general, splice syntax can be remembered as splice (<array-name>, <beginning-index>, <ending-index>)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker