List::MoreUtils is fun.

use List::MoreUtils qw( indexes ); my @array = qw( app Oracle EPDMCA Oracle EPZXC ); defined $array[$_+1] && print "$array[$_+1]\n" for indexes { $_ eq 'Oracle' } @array;

Updated: Allowed for the possibility of 'Oracle' appearing in an 'even' numbered element. At first it seemed like a given that it appears in 'odd' elements, but that's never stated in the question, so it's safer to assume it could appear anywhere in the array. Also allowed for the possibility that there is no element following an instance of 'Oracle'.

Here's a similar approach with grep (eliminating the dependency on List::MoreUtils):

my @array = qw( app Oracle EPDMCA Oracle EPZXC ); print "$array[$_]\n" for grep { $_>0 && $array[$_-1] eq 'Oracle' } 0 .. $#array;

Just for the fun of it, a couple more:

print "$array[$_]\n" for indexes { state $prev = ''; my $compare = $prev; $prev = $_; $compare eq 'Oracle'; } @array;
print "$_\n" for grep { state $ix = -1; my $cmp_idx = $ix++; $cmp_idx >=0 && $array[$cmp_idx] eq 'Oracle'; } @array;

Personally, I think the first 'index' implementation reads the cleanest because it explicitly tells the reader that the output is indices. The first 'grep' solution is a close second, since it eliminates the need for the defined test.

Of course there's also the simple approach:

my @array = qw( app Oracle EPDMCA Oracle EPZXC ); my $ix = 0; while( $ix < $#array ) { print $array[$ix+1] if $array[ix] eq 'Oracle'; $ix++; }

It's hard to beat the good old fashioned while loop.


Dave


In reply to Re: Find Element of array but use the next Element by davido
in thread Find Element of array but use the next Element by emjga

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.