Good morning,

On 10/12/03 at 4:01 PM -0800, wren thornton <[EMAIL PROTECTED]> wrote:

>I'm working with some complex data (array of hashes in
>this case) and I'm wondering if there's a good way to
>do a reverse lookup? So far I have the following:

I'm no expert (& I'd love to hear from one). But when I need to do something
similar I use a second data structure for doing the 'reverse lookup'.

>for my $i (0.. @names-1) {
>   if ($names[$i]{'xml_index'} == $xml_index){
>       $return = $names[$i]{'name'}
>   }
>   last if $return;
>}

So in addition to @names, I would also have %name_xml (& maybe %name_vals
too). 

@names = ({xml_index=>'a', name=>'abc'}, {xml_index=>'d', name=>'def'});
%name_xml = (a=>1, d=>2);   # hash value is index into @names for 
                            # matching xml_index
%name_vals = (abc=>1, def=>2);

You could then do a lookup in @names as:

$val = $names[$name_xml{'a'}]{'name'};

>Which works fine, but I'm pretty sure there has to be
>a more efficient way to do it that will save cycles.

The above will (obviously) take longer to create the data structures and will
use much more memory. So if you only have the occasional lookup to do, it
won't save you anything. But if you have lots of lookups to do, it will save
you time.


Charlie
-- 
   Charlie Garrison    [EMAIL PROTECTED]
   PO Box 141, Windsor, NSW 2756, Australia 

Reply via email to