On 2012.02.06 16:14, sono...@fannullone.us wrote:
I have a web form where people enter their address info and I want to
make sure that the first three digits of their Zip Code correspond to their
State.
So I'm creating a hash of arrays that contains a list of Zip Codes for
the United States. I've also written a foreach loop to access this hash but
I'd like to see if it could be written better. For example, do I really need
three foreach loops?
Also, the first line that's printed contains "499" and I can't figure
out where that's coming from.
I'd appreciate some help.
Thanks,
Marc
#!/Users/perl5/perlbrew/perls/perl-5.14.1/bin/perl
use strict;
use warnings;
my %states = (
AL => [ '350','351', ],
AK => [ '995','996', ],
AZ => [ '850','851', ],
AR => [ '716','717', ],
);
my $customers_state = 'AZ';
my $customers_zip = '850';
my $match = 'no' ;
STATE: foreach my $state (keys %states) {
# print "$state \n";
if ($state eq $customers_state) {
foreach (@{$states{$customers_state}}) {
my @zips = $_;
ZIP: foreach my $zip (@zips) {
next ZIP if $zip ne
$customers_zip;
$match = 'yes';
# print "\nZip matches the
State \n";
}
}
last STATE;
}
}
print $match;
########################
SAMPLE OUTPUT:
499
yes
This may be easier. It uses the hash elements directly as an array, then
uses grep to see if the zip code is within the specific state. It
returns true if the state owns that zip code, and false if it doesn't.
Therefore, if it is true, $match will be set to yes.
#!/usr/bin/perl
use strict;
use warnings;
my %states = (
AL => [ '350','351', ],
AK => [ '995','996', ],
AZ => [ '850','851', ],
AR => [ '716','717', ],
);
my $customers_state = 'AR';
my $customers_zip = '716';
my $match = 'no' ;
if ( grep( /^$customers_zip$/, @{ $states{ $customers_state } } ) ) {
$match = "yes";
}
print "$match\n";
Steve
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/