Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

How do I find the position of an element in an array?

by Zombie lrenigu (Initiate)
on Sep 21, 2001 at 21:52 UTC ( #113951=perlquestion: print w/ replies, xml ) Need Help??
Zombie lrenigu has asked for the wisdom of the Perl Monks concerning the following question:

I wrote a program where I grep for the element from an unknown array (the array keeps incrementing) and want to remove the grepped element. I know I can use splice to remove the element from an array but I need the position of the element to set the OFFSET. Please help.

Comment on How do I find the position of an element in an array?
Re: How do I find the position of an element in an array?
by runrig (Abbot) on Sep 21, 2001 at 22:56 UTC
    my( $i ) = grep { evaluate($array[$_]) } 0 .. $#array;
    Of course, you'd define evaluate() to test for the actual condition you're interested in.
      That should probably be:
      my @deletes = grep { evaluate($array[$_]) } 0..$#@array;
Re: How do I find the position of an element in an array?
by fundflow (Chaplain) on Sep 22, 2001 at 13:22 UTC
    If you need to do this operation many times on an unchanging array, you can use a hash to store the indices. You'd have to re-set the hash any time the array contents changed. You could use an object to encapsulate this mess. :-)
    my @array = ( ... ); my %array_element_index; @array_element_index{ @array } = (0 .. $#array); my $i = $array_element_index{ $value_of_interest };
    Of course, this method and the repeated-greps method both have their own idiosyncratic costs, so which one is more effective/efficient for you really depends on your situations.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (14)
As of 2015-07-02 10:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (33 votes), past polls