评估针对perl数组输入的邮政编码

时间:2011-05-05 09:09:14

标签: regex arrays perl

我有一个数组,其中包含perl中邮政编码区域的起始2个字符,如下所示:

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

我有一个搜索框,用户可以在其中输入部分或完整的邮政编码。我需要检查他们输入的后置代码是否以数组中的一个元素开始,例如,如果他们输入'CV2 1DH',它将评估为true,如果他们输入类似'YO1 8WE'的东西,它将评估为false它不是以其中一个数组值开头的。

现在这对我来说在PHP中很容易做到,但Perl并不是我擅长的东西,到目前为止,我的努力并不是很有成效。

任何想法都会偷看?

4 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分:5)

如果您接受的邮政编码列表足够大,以至于匹配代码中的性能是一个实际问题(可能不是),那么无论如何您最好使用哈希查找而不是数组:

#!/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。

答案 2 :(得分:1)

您可以使用List::Utilfirst或内置的grep

use List::Util 'first';

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

答案 3 :(得分:1)

好的,一个老式的foreach版本,请注意它是一个区分大小写的匹配。 与~~版本有趣地进行基准测试。

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;
}