Perl: Remove elements from a Perl array using Splice

If you need to delete any element from Perl array, what will you do? I know a function at Perl called splice(). Using the function you can easily remove any element or elements from your Perl array. Here goes few example blocks using splice() function.

## my initial array
my @array = qw(1 2 3 4 5 6 7 8 9 10);
## checking the output of my array
print join(' ,', @array) . "\n";

## removing only the elemtns from 5th index(first index = 0)
splice(@array, 5, 1);
print join(' ,', @array) . "\n";


Above example will declare an array of 10 elements from 1 to 10, then it will print all on screen. After that it will remove a single field from the array, and print again. You'll find that one element is deleted.

For your help, here is the properties of the splice() function.

splice ARRAY, OFFSET, LENGTH
# removes anything from the OFFSET index to the index OFFSET+LENGTH-1

splice ARRAY, OFFSET, LENGTH, LIST
# same as the previous, but it will replaces elements removed with those in LIST

splice ARRAY, OFFSET
# removes anything from the OFFSET index till end

Comments