Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way in Perl to iterate a loop and extract pairs or triples

Tags:

arrays

perl

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?

like image 431
Scott Baker Avatar asked Jun 09 '21 01:06

Scott Baker


People also ask

What is Perl foreach?

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.

How do I process an array in Perl?

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.


2 Answers

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" }
like image 121
zdim Avatar answered Sep 23 '22 09:09

zdim


splice is a better way

while (my ($x,$y) = splice @coords, 0, 2) {
    ...
}

Two things to note.

  1. 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) { ... }
    
  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)) { ... }
    
like image 44
mob Avatar answered Sep 23 '22 09:09

mob