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

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?

Replies are listed 'Best First'.
Re: how do I find the position of an element in an unknown array
by dragonchild (Archbishop) on Sep 21, 2001 at 22:51 UTC
    Your question doesn't really make sense. (Unknown array??) However, if you're using grep to find the element, then you can use grep to find everything but the element and use that. Just negate the matching requirements and you should be find.

    Originally posted as a Categorized Answer.

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.
Re: how do I find the position of an element in an unknown array
by QwertyD (Pilgrim) on Apr 04, 2006 at 18:10 UTC

    fundflow's suggestion above to use a hash might be a good idea, but what if the order of the elements in the array is important? You can't just use a hash, because hashes do not preserve any kind of order for their entries.

    What you can use, however, is something like Tie::IxHash which gives you hashes that preserve the order of their entries and upon which you can do array-like operations.

    Originally posted as a Categorized Answer.