Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


Splice

@names=("Muriel","Sarah","Susanne","Gavin");

&look;

@middle=splice (@names, 1, 2);

&look;

sub look {
        print "Names : @names\n";
        print "The Splice Girls are: @middle\n";
}

The first argument for splice is an array. Then second is the offset. The offset is the index number of the list element to begin splicing at. In this case it is 1. Then comes the number of elements to remove, which is sensibly 1 or more in this case. You can set it to 0 and perl, in true perl style, won't complain. Setting to 0 is handy because splice can add elements to the middle of an array, and if you don't want any deleted 0 is the number to use. Like so:

@names=("Muriel","Gavin","Susanne","Sarah");
@cities=("Brussels","Hamburg","London","Breda");

&look;

splice (@names, 1, 0, @cities[1..3]);

&look;

sub look {
        print "Names : @names\n";
        print "Cities: @cities\n";
}

Notice how the assignment to @middle has gone -- it is no longer relevant.

If you assign the result of a splice to a scalar then:

@names=("Muriel","Sarah","Susanne","Gavin");

&look;

$middle=splice (@names, 1, 2);

&look;

sub look {
        print "Names : @names\n";
        print "The Splice Girls are: $middle\n";
}

then the scalar is assigned the last element removed, or undef if it doesn't work at all.

The splice function is also a way to delete elements from an array. In fact, a discussion of :