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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.