我有一个数组,其中包含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并不是我太擅长的东西,到目前为止我的努力并不是很有成效.
有什么想法偷看?
解决方法
如果您接受的邮政编码列表足够大,以至于匹配代码中的性能是一个实际问题(可能不是),那么无论如何您最好使用哈希查找而不是数组:
#!/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,2}) { print "$postcode is OK\n" ; } else { print "$postcode is not OK\n"; }
这种方法适用于5.8.8.