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

Yet another way, using "reverse" and a faked-out "slice":
>perl -e "@arr = qw{ app Oracle EPDMCA Oracle EPZXC Oracle }; print (map {$_ eq 'Oracle'? ($x):($x=$_)[2]} reverse @arr)"

             I hope life isn't a big joke, because I don't get it.
                   -SNL

Replies are listed 'Best First'.
Re^2: Find Element of array but use the next Element
by choroba (Cardinal) on Jun 14, 2012 at 22:01 UTC
    Not getting it. Care to explain?
      Analyzing
      map {$_ eq 'Oracle'? ($x):($x=$_)[2]} reverse @arr
      Ok - reading backwards, the first thing that happens, is @arr gets "reversed".

      Next we process each element of the reversed array. If 'Oracle' is found, we return "$x". You way well ask - what is $x, and where did it get a value?

      That happens if $_ does NOT match. In that case, what happens is:
      * $x gets assigned the current element
      * a temporary LIST is generated because of the () - this contains ($x)
      * We index index into the second element ($x)[2] which does not exist
      *resulting in an EMPTY list
      *That gets sent to "map" which ignores that.

      SO - the only elements that "map" returns is the $x value when the current element is 'Oracle'. In this case, $x contains the value of the previous element, and because we are 'reversed', in real life, it contains the 'next' element.

      There is a potential complaint that the order of the returned values is reversed.
      This is easily fixed by throwing a 'reverse' in front of the 'map'.

                   I hope life isn't a big joke, because I don't get it.
                         -SNL