http://qs321.pair.com?node_id=46316

WebSmart has asked for the wisdom of the Perl Monks concerning the following question:

Hey Monks... I want to be like you all!! What I need to make is a script for an e-commerce site than I am designing. I need to be able to define a hash of 5 to 10 5 digit zip codes. Then I will link that to a form field that will allow the user to enter their zip code in and check if a particular service is available in thier area. Give me some hints.. this is the first script that I have written!

Replies are listed 'Best First'.
Re: Zip Code Script
by merlyn (Sage) on Dec 13, 2000 at 00:28 UTC
    Well, you don't really need a hash. Where is your list of 5-to-10-digit zip codes? Are you getting it from a flat file? From a database? There's no point in making a hash of all those zips unless you plan on using them more than once in a program, and if it's a CGI, then you won't. So skip that step.

    -- Randal L. Schwartz, Perl hacker

      He said (and I think he meant) 5 to 10 FIVE digit zip codes. And I think he was just going to hard code those zip codes in the script. So perhaps something like:
      #!/usr/local/bin/perl -l -w use strict; use CGI; my @zips = qw( 92714 92715 92716 ); my %zips; @zips{@zips} = (); my $q = CGI->new; print $q->header; print $q->start_html; if (my $zip = $q->param('zip')) { print "<br>You entered $zip"; my $valid = (exists $zips{$zip}) ? 'valid' : 'invalid'; print "<br>It is $valid"; } else { print $q->start_form; print $q->textfield(-name=>"zip"); print $q->submit("Go"); print $q->end_form; } print $q->end_html;
      Update: Ok, so you can get rid of the hash and replace 'exists $zip{$zips}' with 'grep { $_ eq $zip } @zips' (see my benchmarks further down this thread), although if you were to port this to mod_perl or the like I'd stick with a hash (though it'd be defined differently) :-)
      A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Zip Code Script
by CoadToad (Acolyte) on Dec 13, 2000 at 03:55 UTC
    I also want to suggest that you consider picking up Learning Perl

    This book gives a good explaination of things such as arrays and hashes.
Re: Zip Code Script
by HamNRye (Monk) on Dec 13, 2000 at 01:22 UTC

    Randal has a point...

    However, I see a use for a hash in the form of

    %hash{$zip$;service}
    My preferred method (TMTOWTDI) would be to keep an array of zips for an index and then a hash keyed by index with services.
    foreach $ourzips (@zipcodes) { if ($userzip eq $ourzips) { $service = %hash{$userzip, service} ; } else { $service = "No service available. Loooooser!" ; } }
    Have fun!