Evaluate entered zip codes against perl array

I have an array that contains the initial 2 characters of zip codes in perl, for example:

@acceptedPostcodes = ("CV", "LE", "CM", "CB", "EN", "SG", "NN", "MK", "LU", "PE", "ST", "TF", "DE", "WS");

I have a search box in which the user enters a part or full postal code. I need to check if the zip code he entered started with one of the array elements, for example, if they entered “CV2 1DH”, it would evaluate to true, and if they entered something like “YO1 8WE”, it will be false , it does not start with one of the array values.

Now it would be easy to do in PHP for me, but Perl is not too good, and so far my efforts have not been very fruitful.

Any idea visible?

+3
source share
4 answers

, (, , ), , , - :

#!/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";
}

5.8.8.

+5

Smart Match (~~) - ( substr, .

#!/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";
}
+5

You can use or builtin:List::Util firstgrep

use List::Util 'first';

my $postcode = substr $input, 0, 2;    
my $status = (first {$_ eq $postcode} @acceptedPostcodes) ? 1 : 0;
+1
source

Well, an old-fashioned version of foreach, note that it matches a case-sensitive match. Interesting about the same as the ~~ version. Interesting.

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;
}
+1
source

All Articles