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

Re: Find last position of an element in array

by dbuckhal (Chaplain)
on Mar 29, 2022 at 17:38 UTC ( [id://11142504]=note: print w/replies, xml ) Need Help??


in reply to Find last position of an element in array

skipping past the sigil or brace mismatch, here is my five minute contribution...

perl -le ' my @arr = (1,1,1,2,2,2,2,2,3,3,3,4,4,4,4,4,4,5,5,6); print (@arr - index((reverse(@arr)), 4)); ' __output__ 17

Replies are listed 'Best First'.
Re^2: Find last position of an element in array
by kcott (Archbishop) on Mar 29, 2022 at 21:49 UTC

    G'day dbuckhal,

    17 = off-by-one error. Fix: use $#arr instead of @arr.

    $ perl -le ' my @arr = (1,1,1,2,2,2,2,2,3,3,3,4,4,4,4,4,4,5,5,6); print ($#arr - index((reverse(@arr)), 4)); print "@arr[16, 17]"; ' 16 4 5

    — Ken

Re^2: Find last position of an element in array
by hippo (Bishop) on Mar 30, 2022 at 09:49 UTC

    You can avoid the maths with rindex:

    $ perl -le ' my @arr = (1,1,1,2,2,2,2,2,3,3,3,4,4,4,4,4,4,5,5,6); print rindex( join (q{}, @arr), 4 ); ' 16

    🦛

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (2)
As of 2024-04-19 21:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found