Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluate entered postcodes against perl array

Tags:

arrays

regex

perl

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?

like image 815
azzy81 Avatar asked Sep 14 '26 22:09

azzy81


2 Answers

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.

like image 133
Dave Sherohman Avatar answered Sep 16 '26 19:09

Dave Sherohman


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";
}
like image 27
Quentin Avatar answered Sep 16 '26 18:09

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!