in reply to searching 2 arrays
The point that I would make is, the input array is best handled as an array, because you want to preserve the order when you're checking the existence of entries in it. But the database array should be converted to a hash, because you want to quickly check it for existence of keys which match the input values. You certainly don't want to do a nested loop, if for no other reason than, in a case where you have a lot of data, you'll be making the algorithm needlessly slow.#!/usr/bin/perl -w + # Strict use strict; use warnings; + # Data my @DB = qw( AB1/1 AB1/5 AB2/5); my @Input = qw( AB1/1 AB1/2 AB1/5 AB1/6 AB1/9 AB2/2 AB2/5 AB2/6 AB2/9 +AB2/13 ); + # Main program &show_me("From DB", \@DB); &show_me("From Input", \@Input); + # Make a hash from the DB array, and run the Input list looking for ma +tches my %DB = map { $_ => 1 } @DB; foreach my $input (@Input) { my $result = defined($DB{$input})? "Found": "NotFound"; printf "%s : %s %s\n", $input, $result, $input; } # Subroutines sub show_me() { my ($msg, $pdata) = @_; print "$msg:\n"; map { printf " %s\n", $_ } @$pdata; print "\n"; }
|
|---|