Showing entries with tag "Pair".

Found 1 entries

Perl: Loop through an array an extract pairs of variables

I had an array that I wanted to iterate through and extract pairs of variables. I found this pretty neat way to do that:


my @arr = ("red", "green", "blue", "yellow", "orange", "purple");

while (@arr) {
    my ($x, $y) = splice(@arr, 0, 2);
    print "$x:$y\n";

I found a bunch of different ways to do this, and benchmarked them.


$arr = ["red", "green", "blue", "yellow", "orange", "purple"];

while ($arr) {
    [$x, $y] = array_splice($arr, 0, 2);
    print "$x:$y<br />";

Note: You need to be careful you have an even number of elements or you will get undefined variable errors.

Leave A Reply