in reply to Re: Global variables question
in thread Global variables question

Hi Marshall,

Thank you for your detailed response very well explained. As you can tell i'm quite new to this so I will work on my indenting to make my code clearer in the future. Just for my understanding... is there a difference betwen a hash and a 2D array or is a hash table more efficient? Also for the compare part I want to compare the files as you described in the last part of your answer. Would something like this be on the right lines?

my $found = 0;
foreach my $key1 (keys %hash1) {
foreach my $key2 (keys %hash2) {
if ($hash1{$key1} eq $hash2{$key2})

{
$found=1;
}
print "$found";
}
}

Replies are listed 'Best First'.
Re^3: Global variables question
by Marshall (Canon) on Aug 24, 2010 at 16:50 UTC
    I figure you still have some indenting work to do. This is very important. Judiciously applied white space is one of the very most important things that you can do to improve readability of your code.

    Untested, but I figure close to what you want...test, experiment, move forward with the advice you've gotten so far...

    my $num_errors = 0; foreach my $file (keys %hash1) { if (!exists ($hash2{$file}) ) { print "file: $file doesn't exist in 2nd directory\n"; } elsif ($hash1{$file} ne $hash2{$file}) { print "md5 didn't match for $file\n"; # meaning that file in 2nd directory is not the # same as the file in 1st directory $num_errors++; } } print "total errors = $num_errors\n";
    Perl "sees" something akin to this (below)... a bit harder to understand than the above?
    white space is important, variable names are important.
    I called my hashes %dirA and %dirB instead of %hash1 and %hash2 for a reason!

    %x is a hash but "x" has no contextual meaning! %dirA is a hash of file names in directory A to checksums.
    Even %dirA_files_to_checksums would be wayyyyyy better than %hash1. I guess %dir1 is also ok. The % means hash - give more contextual information!

    my $num_errors=0;foreach my $file (keys %hash1){if (!exists ($hash2{$f +ile})){print "file: $file doesn't exist in 2nd directory\n";}elsif ($ +hash1{$file} ne $hash2{$file}){print "md5 didn't match for $file\n";$ +num_errors++;}}print "total errors = $num_errors\n";
    PS: Yes, a hash tables for this purpose is going to be WAY more efficient than an array.
      Thanks Marshall,

      By the way I was not planning to use %hash1 etc in my code it was just something I quickly scribbled down to test my logic but thanks! Will work on my indenting too! You've been a great help.

        Keep after it! I wish you well. Didn't mean to blare too many horns from my high horse! Working now on fixing a set of C++ code and although completely unrelated, a little frustration bled over. Forgive me.