Warning: Undefined array key "action" in /home/bakers/html/entryreply.php on line 5

Warning: Undefined variable $output in /home/bakers/html/entryreply.php on line 50

Warning: Undefined array key "EntrySubject" in /home/bakers/html/entryreply.php on line 51

Warning: Undefined variable $logintext in /home/bakers/html/entryreply.php on line 97

Warning: Undefined variable $reply_name in /home/bakers/html/entryreply.php on line 103

Warning: Undefined variable $reply_email in /home/bakers/html/entryreply.php on line 104
Perturb.org - interesting technology related things from around the internet

Perl: Loop through an array and 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:

Perl:

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.

PHP:

$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.



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 44.197.197.23
To prevent spam please submit by clicking the kitten: