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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access