[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [coldsync-hackers] New Perl question; Do I need to keep both a hash and an array?



On Saturday 07 June 2003 15:32, Izzy Blacklock wrote:
> Is there a way around needing to populate both an array and a hash?

Populating, yes. Using, maybe.

If order matters, a hash by itself won't quite work. For your first usage 
where you're essentially just doing a search against a known value, 
something like this works fine:

    my %NamesHash;
    foreach my $record (@{$pdbs{TitraxNameDB}->{records}}) {
                my $text = $record->{data};
                $text =~ s/\\/\\\\/g;
	        $NamesHash{$text} = $text;
     }

All you'd need to do now is use the "exists" function:

  foreach my $record (@{$pbds{DatabookDB}->{records}}) {
  	next unless exists $NamesHash{ $record->{"description"} };
  	... stuff ...
  }

For your second example, things are a little more complicated. First, 
however, I have to ask a question... Are you absolutely positive that the 
record ordering between two different databases is going to be the same? 
You seem to be assuming that record $i in TitraxNameDB is the same as 
record $i in TitraxNoteDB. I'm not sure how Titrax organizes its databases, 
so I have to ask. Record ordering isn't always under the control of one 
app. Sync, for example, could mess with it.

Assuming you _can_ make the assumption, you need to modify the creation code 
as follows:

    my %NamesHash;
    my $i = 0;
    foreach my $record (@{$pdbs{TitraxNameDB}->{records}}) {
                my $text = $record->{data};
                $text =~ s/\\/\\\\/g;
	        $NamesHash{$text} = $i ++;
     }

In order to use it, you're almost certainly going to need to make some kind 
of temporary array similar to what you already had because you need to 
preserve the ordering. Something like:

  my @nhSorted =
    sort { $NamesHash{$a} <=> $NamesHash{$b} } (keys %NamesHash);

  my $i = 0;
  foreach my $record (@{$pdbs{TitraxNoteDB}->{records}}) {
    my $description = $nhSorted[$i++];

    ... stuff ...
  }

The gist is that you don't need to build two separate objects that have 
essentially the same data. You can generate the array from the hash. You 
could also do it the other way around if you needed to.

I would, however, question the ordering. If I were doing something where I 
was creating two separate cross-referenced databases, I'd probably be using 
some kind of record identifier. Palm records all have unique id's, so that 
would be my first guess. I don't suppose TitraxNoteDB records have a field 
something like "nameid" or some such, huh?

c.

-- 
This message was sent through the coldsync-hackers mailing list.  To remove
yourself from this mailing list, send a message to majordomo@thedotin.net
with the words "unsubscribe coldsync-hackers" in the message body.  For more
information on Coldsync, send mail to coldsync-hackers-owner@thedotin.net.