On Mon, Feb 6, 2012 at 3:14 PM, <[email protected]> wrote:
> 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?
>
<snip>
> #!/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;
>
You can also key the hash with the first three digits and skip the loops
altogether.
> my %zips = (
350 => 'AL',
351 => 'AL',
995 => 'AK',
996 => 'AK',
850 => 'AZ',
851 => 'AZ',
716 => 'AR',
717 => 'AR',
);
> my $customers_state = 'AZ';
my $customers_zip = '850';
if (
exists( $zips{$customers_zip} )
and $zips{$customers_zip} eq $customers_state
) { print 'yes'; }
else { print 'no'; }
--
Robert Wohlfarth