linux poison RSS
linux poison Email

Perl Script: Insert, Replace or Delet the range of elements from an Array - splice

The Perl splice function is an array manipulation function and is used to remove, replace or add elements.
splice (@ARRAY, OFFSET, LENGTH, LIST)
where:
ARRAY - is the array to manipulate
OFFSET - is the starting array element to be removed
LENGTH - is the number of elements to be removed
LIST - is a list of elements to replace the removed elements with

The splice function returns:
in scalar context, the last element removed or undef if no elements are removed
in list context, the list of elements removed from the array

Below is simple perl script which demonstrate the use of this splice function, feel free to use and copy this code

Source: cat splice.pl
#!/usr/bin/perl

@array = ("1", "2", "3", "4");
@insert = ("two", "three", "four");

# skips over the first element, and replaces the next two elements ("2" and "3")  with the list ("two", "three", "four").
$var = splice (@array, 1, 2, @insert);

if (defined($var)) {
        print "Now, new array is: @array \n";
} else {
        print "Something went wrong :( \n";
}

# Delete the range of element.
$var1 = splice(@array, 1, 3);
if (defined($var1)) {
        print "Now, after deletion, array is: @array \n";
} else {
        print "Something went wrong :( \n";
}


Output: perl splice.pl
Now, new array is: 1 two three four 4
Now, after deletion, array is: 1 4 




0 comments:

Post a Comment

Related Posts with Thumbnails