home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


4.11. Processing Multiple Elements of an Array

Problem

You want to pop or shift multiple elements at a time.

Solution

Use splice :

# remove $N elements from front of @ARRAY (shift $N)
@FRONT = splice(@ARRAY, 0, $N);

# remove $N elements from the end of the array (pop $N)
@END = splice(@ARRAY, -$N);

Discussion

It's often convenient to wrap these as functions:

sub shift2 (\@) {
    return splice(@{$_[0]}, 0, 2);
}

sub pop2 (\@) {
    return splice(@{$_[0]}, -2);
}

This makes their behavior more apparent when you use them:

@friends = qw(Peter Paul Mary Jim Tim);
($this, $that) = shift2(@friends);
# $this contains Peter, $that has Paul, and
# @friends has Mary, Jim, and Tim

@beverages = qw(Dew Jolt Cola Sprite Fresca);
@pair = pop2(@beverages);
# $pair[0] contains Sprite, $pair[1] has Fresca,
# and @beverages has (Dew, Jolt, Cola)

splice returns the elements removed from the array, so shift2 replaces the first two elements in @ARRAY with nothing (i.e., deletes them) and returns the two elements it deleted. In pop2 , the last two elements at end of the array are removed and returned.

These two functions are prototyped to take an array reference as their argument to better mimic the built-in shift and pop functions. The caller doesn't pass in an explicit reference using a backslash. Instead, the compiler, having seen the array reference prototype, arranges to pass the array by reference anyway. Advantages to this approach include efficiency, transparency, and compile-time parameter checking. One disadvantage is that the thing passed in must look like a real array with a leading @ sign, not just a scalar containing an array reference. If it did, you'd have to prepend an @ , making it less transparent:

$line[5] = \@list;
@got = pop2( @{ $line[5] } );

This is another example of where a proper array and not a mere list is called for. The \@ prototype requires that whatever goes in that argument slot be an array. $line[5] isn't an array, but an array reference. That's why we need the "extra" @ sign.

See Also

The splice function in perlfunc (1) and Chapter 3 of Programming Perl ; the "Prototypes" sections of perlsub (1) and Chapter 2 of Programming Perl ; we use splice in Recipe 4.9


Previous: 4.10. Reversing an Array Perl Cookbook Next: 4.12. Finding the First List Element That Passes a Test
4.10. Reversing an Array Book Index 4.12. Finding the First List Element That Passes a Test