Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: lsearch for perl?

by ikegami (Patriarch)
on Dec 05, 2005 at 15:45 UTC ( #514158=note: print w/replies, xml ) Need Help??


in reply to lsearch for perl?

$found = 0; @list = grep { $item ne $_ || $found++ } @list;

or

my ($index) = grep { $item eq $list[$_] } 0..$#list; splice(@list, $index, 1) if defined $index;

or

use List::Util qw( first ); my $index = first { $item eq $list[$_] } 0..$#list; splice(@list, $index, 1) if defined $index;

Update: Tested. Fixed flawed grep rule.

Replies are listed 'Best First'.
Re^2: lsearch for perl?
by shenme (Priest) on Dec 05, 2005 at 17:50 UTC
    or
    use List::MoreUtils qw( first_index ); my $index = first_index { $item eq $_ } @list; # Returns -1 if no such item could be found.
Re^2: lsearch for perl?
by matt.tovey (Beadle) on Dec 06, 2005 at 08:52 UTC
    Thanks to all for your replies - they were all very helpful.

    Things like this

    @list = grep { $item ne $_ } @list;
    aren't in the man-page, and got me thinking. This however:
    my ($index) = grep { $item eq $list[$_] } 0..$#list; splice(@list, $index, 1) if defined $index;
    was a real satori, Keanu-Reeves-like "Whoah!!" moment for me. The idea of using grep on a list without naming _that_ list as the argument to grep would never have occurred to me. Guess I was stuck in Unix grep thinking!

    Feeling quite humbled.

      Things like this aren't in the man-page

      grep accepts any code in the block. It doesn't have to be a regex. grep is useful for filtering out items from a list, while map is useful for transforming a list.

      The idea of using grep on a list without naming _that_ list as the argument to grep would never have occurred to me.

      It's an concept I picked up on PerlMonks too :)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2022-12-03 01:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?