Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, Iam trying to compare two "hash of arrays". The idea is to compare the values, subtract and Input into Database. The following pseudocode is what i thought up. Is this approach correct?
#####Pseudo Code begins...
<br> $datainput=DBI->connect<br>("DBI:mysql:database=DATA;host=localhost... +...)<br> foreach ($hash1($key1))<br> {<br> foreach ($hash2($key2))<br> {<br> if $hash1($key1)==$hash2($key2)<br> {<br> $data1=$hash2($value1)-$hash1($key2);<br> $data2=$hash2 ($value2)-$hash2(key2);<br> $datainput->do("INSERT INTO DATA VALUES($data1, $data2)<br> }<br> }<br> }<br> $datainput->disconnect();<br> exit;<br>
#####Pseudo Code ends...
Rgds,

Replies are listed 'Best First'.
Re: Hash of Array Comparision...
by chromatic (Archbishop) on Dec 01, 2001 at 12:08 UTC
    Nothing obviously wrong jumps out at me, though I'm not sure why you switch from $key1 and $key2 to $value1 and $value2. There's probably an easier way to do it without looping through all of the keys multiple times.

    Even if you do minimize the looping, there will be a performance penalty for your do() call within the loop. Better to prepare a statement with placeholders outside and execute it repeatedly.

    my $dbh = DBI->connect("DBI:mysql:database=DATA;..."); my $sth = $dbh->prepare("INSERT INTO DATA VALUES(?, ?)"); foreach my $key (keys %hash1) { # check other hash $sth->execute($data1, $data2); }
Re: Hash of Array Comparision...
by jlongino (Parson) on Dec 01, 2001 at 12:27 UTC
    I don't think it will work the way you have this set up. I'm ignoring the database component but imagine you'll want to do something more like this:
    use strict; my %hash1 = (1=>[5,4,3,2,1], 2=>[1,2,3], 3=>[8,9]); my %hash2 = (1=>[6,5,4,3,2], 3=>[4,5]); foreach my $key1 (keys %hash1) { if (exists $hash2{$key1}) { foreach my $ss (0..@{$hash1{$key1}}) { ## do subtraction here using $ss as subscripts: ## my $data1 = $hash1{$key1}[$ss] - $hash2{$key1}[$ss]; ## it's not clear from your code why you're subtracting ## keys from values. } } }
    HTH.

    --Jim