I have a flat array of coordinates and I want to iterate and extract pairs of x and y coordinates. The same logic could apply to triples for RGB colors. This is what I have so far, but it doesn't feel super flexible or elegant.
my @coords = qw(1 5 2 6 3 8 6 12 7 5);
for (my $i = 0; $i < @coords; $i += 2) {
my $x = $coords[$i];
my $y = $coords[$i+1];
print "$x, $y\n";
}
There has to be a better way to do this right?
A foreach loop runs a block of code for each element of a list. No big whoop, “perl foreach” continues to be one of the most popular on Google searches for the language.
Perl arrays are dynamic in length, which means that elements can be added to and removed from the array as required. Perl provides four functions for this: shift, unshift, push and pop. shift removes and returns the first element from the array, reducing the array length by 1.
The module List::MoreUtils has natatime
(n-at-a-time)
use List::MoreUtils qw(natatime);
my @ary = 1..12;
my $it = natatime 3, @ary; # iterator
while (my @triplet = $it->()) { say "@triplet" }
splice
is a better way
while (my ($x,$y) = splice @coords, 0, 2) {
...
}
Two things to note.
splice
consumes the elements of @coords
. If you don't want your loop to destroy the contents of your array, use a temporary array.
my @tmp = @coords;
while (my ($x,$y) = splice @tmp,0,2) { ... }
If the input might not contain an even number of elements, you may want to add an additional check to make sure each iteration has access to the right number of elements
while (2 == (my ($x,$y) = splice @coords,0,2)) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With