http://qs321.pair.com?node_id=1216189


in reply to Fence vs. Posts

Here is another complicated "perlish" solution to avoid simple C-style loops as proposed above (and which is the most sensible approach IMHO), this time using closures:

se warnings; use strict; sub create_scheduler { my $list = shift; return sub { my $i = shift; return () if $i > $#$list - 1 or $i < 0; return ( $list->[$i], $list->[$i+1] ); } }; my $leg = create_scheduler [ "Chicago", "Saint Looey", "Joplin", "OKC" +, "Amarillo", "Gallup", "Flagstaff", "Winona", "Kingman", "Barstow", +"San Bernandino", "LA" ]; my $i = 0; while( my @pair = $leg->($i++) ) { print join( " to ", @pair ), "\n"; }

You could also "enclose" the index into the closure if you want to create a one-time iterator over your array.