in reply to Print both elements in a compare

The reason why you're seeing an error is because the test above (the code you have quoted) is checking for the existence of the value $hash{$key} which returns undefined if there's nothing there (IE false). In the second code snippet you're trying to access an element that may or may not exist. In the case that the value you're trying to access doesn't exist ($hash{$key}) then you're asking for perl to access a nonexistant value in a data structure. I think that's the error you're getting. What it sounds like you're trying to do is roll through both arrays simultaneously determining if there's a problem as you go along. you could to some degree combine both operations but it's not exactly clean. instead of:
my %hash; for my $key (@array2){ $hash{$key}++; } for my $key (@array1){ print "Fail: %key \n" unless $hash{$key}; }
Try putting them together something like:
for my $key (@array2){ $hash{$key}++ print "Fail $key" unless grep($key, @array1); }
Two notes about that however. The first is that you don't know from this what the key is in array 1 that has caused the error, you just know which key mismatches. Second, if you have an array of numbers and one of them is 0 you'd return a false value for that grep. What I'd really recommend is a destructive process on the arrays. If you really need to keep those two alive then you can copy them.
my $hash; while (@array1){ my $var1 = shift @array1; my $var2 = shift @array2; if($var1 == $var2){ $hash{$var1}++; } else { print "Key mismatch array1 value $var1 != $var2 (array2 value)"; } }
The one note about the above code is that if array1 and array2 are not the same length you're gonna have a fatal error and die.

Replies are listed 'Best First'.
Re^2: Print both elements in a compare
by Anonymous Monk on Nov 01, 2010 at 19:16 UTC
    Ah OK I understand why it's happening now. I can stick a check in for the array length prior to running this to avoid the fatal error you are on about. Is there anyway to do this without a destructive process on the arrays ?
      Use my compare2(), or List::Compare or Array::Compare.