splice()

Copy the text below and run it as a Perl script.


# splice takes two required and two optional arguments:
#
#     splice(@array, offset=index, [length], [list])
#
# @array is the array that will have elements removed or replaced;
# offset is the index of the first element to be removed or replaced;
# length is the number of elements to remove
# list   is a list of elements to replace the removed elements

# if no length is given, everything beginning with the offset element
# will be removed

# if list is given, the removed elements will be replaced by the list;
# NOTE: if you pass a replacement list to the function, you must also
# specify the number of elements to be removed (length); 
# if the length value is 0, nothing will be removed but the replacement
# list will be inserted at the offset value

# splice() returns an array of the removed elements;
# the original array will shrink or grow as needed



# first, create arrays
@myArray     = ("Hansel", "Gretel", "Rambo", "Ted", "Alice");
@substitutes = ("Gilda", "Rigoletto");

print "@myArray\n\n";

# second, remove Rambo and print
# ==> remove one element starting at offset 2

@returned = splice(@myArray, 2, 1);
print "@returned\n@myArray\n\n";

# third, insert second array
# change the length value to see how the replacement works

@returned = splice(@myArray, 2, 0, @substitutes);
print "returned: " . @returned . "\n\n"; # @returned is evaluated in scalar context
print "@myArray\n";