in reply to Re: Re: Searching a database
in thread Searching a database
my %matches = map {$_ => 1} 17, 83, 114, 205, 407; OUTER: while (my ($key, $value) = each %hash) { foreach my $num (split /::/ => $value) { if ($matches {$value}) { print "$key: $value\n"; last OUTER; } } }
Abigail
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Searching a database
by hmerrill (Friar) on Sep 12, 2003 at 13:11 UTC | |
mystifies me - what is the split splitting? When split isn't given an arg to split, it splits $_, but what is $_ in this case, since the while loop gets $key and $value? IMHO, more straightforward code, albeit sometimes longer code, is better: I'm not entirely sure I understand the original intent, so this solution may need some work. HTH. | [reply] [d/l] [select] |
by Abigail-II (Bishop) on Sep 12, 2003 at 13:35 UTC | |
I have no problem with the while, but the foreach:mystifies me - what is the split splitting? When split isn't given an arg to split, it splits $_ split() splits its second argument, if any. In the quoted line, the second argument of split() is $value.
MHO, more straightforward code, albeit sometimes longer code, is better: I spot two differences. First one is that you replace the split inside the foreach into two lines, introducing an extra variable:
I'm not convinced of any gain here. The second one is that you replace a labelled last with a Pascal/Cish equivalent: setting a flag in the inner loop, and testing for it in the outer loop. This is what the documentation (and I hear Larry's voice when I read it) has to say about it:
The documentation calls the use of labelled loop control cleaner, safer, faster. And you prove the documentation right. Your would, after translating the Python syntax to Perl syntax, contributes *nothing at all*. It's at the end of the loop and doing the next iteration is what's going to happen anyway. It means that your code is going to inspect all key-value pairs of the hash, instead of bailing out when a matching value is found. Bailing out early is more efficient, and correct, because it's given that there is at most one matching value. It's not that my algorithm is flawless, it does contain something to pick a nit over: it leaves the hash iterator as is. But that could be easily resolved by doing an 'keys %hash' after the while loop. Abigail | [reply] [d/l] [select] |