Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Testing if an array contains a value and then deleting it in most efficient way

by jwkrahn (Abbot)
on Feb 19, 2008 at 04:52 UTC ( [id://668731]=note: print w/replies, xml ) Need Help??


in reply to Testing if an array contains a value and then deleting it in most efficient way

  1. Use a hash.

  2. @array = grep $_ != $value, @array;

  3. Or a fairly efficient method:

    for my $i ( 0 .. $#array ) {
        if ( $array[ $i ] == $value ) {
            @array[ $i, -1 ] = @array[ -1, $i ];
            $#array--;
            last;
            }
        }


  1. Update: after my naive attempt at efficiency and some benchmarking this works better:

    my $i
    for ( @array ) {
        if ( $_ == $value ) {
            $i = $_;
            last;
            }
        }
    splice @array, $i, 1;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-26 03:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found