Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
We don't bite newbies here... much
 
PerlMonks  

Re: Idiomatic Array Index Search?

by jorg (Friar)
on May 26, 2001 at 22:03 UTC ( [id://83554]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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....

    Jorg

    "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 04: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?
    Username:
    Password:

    What's my password?
    Create A New User
    Domain Nodelet?
    Node Status?
    node history
    Node Type: note [id://83554]
    help
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Notices?
      hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
      erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.