I have an array which contains the starting 2 characters of postcode areas in perl like so:
@acceptedPostcodes = ("CV", "LE", "CM", "CB", "EN", "SG", "NN", "MK", "LU", "PE", "ST", "TF", "DE", "WS");
I have a search box where a user will type in part or a full post code. I need to check if the post code they entered started with one of the elements of the array so for example if they entered 'CV2 1DH' it would evaluate to true and if they entered something like 'YO1 8WE' it would evalute to false as it doesn'开发者_开发知识库t start with one of the array values.
Now this would be easy to do in PHP for me but Perl isnt something im too good at and so far my efforts havn't been very fruitful.
Any idea peeps?
If your list of accepted postcodes is large enough that performance in the matching code is an actual concern (it probably isn't), you'd probably be better off using a hash lookup instead of an array anyhow:
#!/usr/bin/perl
use strict;
use warnings;
my %accepted_postcodes = ("CV" => 1, "LE" => 1, "CM" => 1, "CB" => 1, "EN" => 1, "SG" => 1, "NN" => 1, "MK" => 1, "LU" => 1, "PE" => 1, "ST" => 1, "TF" => 1, "DE" => 1, "WS" => 1);
# Or, to be more terse:
# my %accepted_postcodes = map { $_ => 1 } qw(CV LE CM CB EN SG NN MK LU PE ST TF DE WS);
my $postcode = "CV21 1AA";
if (exists $accepted_postcodes{substr $postcode, 0, 2}) {
print "$postcode is OK\n" ;
} else {
print "$postcode is not OK\n";
}
This method will work fine with 5.8.8.
Smart Match (~~
) is your friend here (after you use substr
to get the first two letters from the entered string.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
my @acceptedPostcodes = ("CV", "LE", "CM", "CB", "EN", "SG", "NN", "MK", "LU", "PE", "ST", "TF", "DE", "WS");
my $postcode = "CV21 1AA";
if ((substr $postcode, 0, 2) ~~ @acceptedPostcodes) {
say "$postcode is OK" ;
} else {
say "$postcode is not OK";
}
Ok, an old fashioned foreach version, note that it does a case sensitive match. Benchmarked about the same as the ~~ version interestingly.
sub validatePostcode($)
{
my ($testPostcode) = @_;
my @acceptedPostcodes = ("CV", "LE", "CM", "CB", "EN", "SG", "NN", "MK", "LU", "PE", "ST", "TF", "DE", "WS");
$testPostcode = substr($testPostcode, 0, 2);
foreach my $postcode (@acceptedPostcodes)
{
if($postcode eq $testPostcode)
{
return 1;
}
}
return 0;
}
You can use List::Util
's first
, or the grep
builtin:
use List::Util 'first';
my $postcode = substr $input, 0, 2;
my $status = (first {$_ eq $postcode} @acceptedPostcodes) ? 1 : 0;
精彩评论