Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Idiomatic Array Index Search?

by jorg (Friar)
on May 27, 2001 at 02:03 UTC ( #83554=note: print w/replies, xml ) Need Help??

in reply to Idiomatic Array Index Search?

I think you just need a reassuring pad on the back here footpad

  • You're looking for a direct case sensitive match and used eq, which is perfect.
  • You want to preserve the order of the values. You could build a hash where the key is the arrayindex of the value. eg my %data = (     1 => 'test1', 2 => 'test2', 3 => 'test3); I would see this as unnecessary complication. The usage of an array is perfectly adequate here.
  • Grep is inefficient yes because it searches ALL the matches and thus always loops your entire list.

    Basically I like the code you've written, it's easy to understand, maintainable, fits it's purpose and didn't take you long to write.
    Now if only all code was as easy this....


    "Do or do not, there is no try" -- Yoda

  • Replies are listed 'Best First'.
    Re: Re: Idiomatic Array Index Search?
    by Vynce (Friar) on May 27, 2001 at 08:51 UTC

      i agree that footpad has nothing to worry about here. however, i think the hash solution that makes sense isn't the one you argued against.

      there's a hash solution that makes sense if three things are true:

      1. you're finding indices in this list fairly often
      2. you're changing the array fairly rarely
      3. you have no repeats or a simple decision making process about what to do with them.

      what do i mean by "fairly" often and "fairly" frequently? i think probably if you are looking up 3 for each change you make to the array, and you can capture all array changes, then this is a good solution. as for #3, i'll assume you always want the 1st occurence.

      the idea is, basically, to construct a lookup hash where for any $array[$i] == $value, there's $lookup{$value} == $i. for instance, you might write it this way:

      { my %lookup; sub _init_lookup_hash { %lookup; for my $i (0..$#_) { $lookup{$_[$i]} = $i unless defined $lookup{$_[$i]}; } } sub list_index { return $lookup{$_[0]} or -1 } ; }


    Log In?

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

    How do I use this? | Other CB clients
    Other Users?
    Others lurking in the Monastery: (3)
    As of 2021-09-19 00:11 GMT
    Find Nodes?
      Voting Booth?

      No recent polls found