Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Find Element of array but use the next Element

by davido (Archbishop)
on Jun 14, 2012 at 16:01 UTC ( #976245=note: print w/replies, xml ) Need Help??

in reply to Find Element of array but use the next Element

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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://976245]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2016-10-22 18:12 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (297 votes). Check out past polls.