Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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.


Dave


Comment on Re: Find Element of array but use the next Element
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2014-08-23 01:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (169 votes), past polls