arraysperlelement

Remove elements of a Perl array


Is there an easy way to remove n consecutive elements of a Perl array (thus making it shorter in length)?


Solution

  • You are looking for the Perl builtin function splice, which lets you pick a starting point, number of elements to remove, and an optional replacement list.

    my @array = 0 .. 9;
    
    my @slice = splice @array, 3, 3;
    
    say "@slice";   # prints "3 4 5"
    say "@array";   # prints "0 1 2 6 7 8 9"
    say 0 + @array; # prints 7