Sometimes what I do for this is:
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.


In reply to Re: Getting the next array element while still keeping the current one by ff
in thread Getting the next array element while still keeping the current one by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.