http://qs321.pair.com?node_id=514158


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 :)