in reply to Getting the next array element while still keeping the current one
my @array = qw( wilma fred barney betty ); foreach my $i ( 0 .. $#array ) { print "$array[ $i ] is the current element.\t"; print "The next element is "; # Before using the next element, test for its existence. print exists $array[ $i + 1 ] ? $array[ $i + 1 ] : "unprintable" ; print ".\n"; # An approach more to your liking might be: # if ( exists $array[ $i + 1 ] ) { # or: # last if $i == $#array; # or: # print $array[ $i + 1 ] unless $i == $#array; # }
Other times, like after I've already written my loop but I need to expand its powers to be able to access the next element, I might do:
use strict; my @array = qw( wilma fred barney betty ); my $ctr = 0; my $next_name; foreach my $name ( @array ) { print "$name is the current element.\t"; # Before using the next element, test for its existence. $next_name = exists $array[ $ctr + 1 ] ? $array[ $ctr + 1 ] : "unavailable" ; # Or you could break out immediately or perhaps have some # "end of array" code: # last if $next_name eq 'unavailable'; # or: # if ( $next_name eq 'unavailable' ) { # # do whatever you do when no more elements # } print "The next element is $next_name.\n"; } continue { $ctr ++; } # Use of the '} continue {' line is more fancy than necessary; # It's useful if you plan to break out of your loop with # a 'next' command.
Note that while and for have their own ways of letting you set up these loops. I'm just in something of a rut of using foreach (which could be shortened to for) and twist things as above in order to use its approach.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Getting the next array element while still keeping the current one
by NetWallah (Canon) on May 02, 2004 at 14:26 UTC | |
by parv (Parson) on May 02, 2004 at 18:23 UTC | |
by NetWallah (Canon) on May 03, 2004 at 16:32 UTC | |
by parv (Parson) on May 05, 2004 at 04:58 UTC |