Match and Count

S

sidel

Hello,

I have a csv with name, address, city, state, zip (XXXXX-XXXX). I am hoping
to group all the similiar zip codes and produce a count on each group. My
match so far is m/^\d{5}-\d{4}$/ A match by the first five is ok, but how
would I roll through each one? (for example 90210, 90211, 90213 ...)

thanks
JS
 
R

Roy Johnson

sidel said:
A match by the first five is ok, but how
would I roll through each one? (for example 90210, 90211, 90213 ...)

1. You'll probably get more responses at comp.lang.perl.misc or
perl.beginniers. This newsgroup does not exist in the official list.
2. What do you mean by the question I've quoted above?
 
J

Jim Gibson

sidel said:
Hello,

I have a csv with name, address, city, state, zip (XXXXX-XXXX). I am hoping
to group all the similiar zip codes and produce a count on each group. My
match so far is m/^\d{5}-\d{4}$/ A match by the first five is ok, but how
would I roll through each one? (for example 90210, 90211, 90213 ...)

thanks
JS

Use parentheses to capture the 5-digit zip code, then a hash to count
the entries (untested):

my %count;
while(...) # whatever loop you have
if( /^(\d{5})-\d{4}$/ ) {
$count{$1}++;
}
}

foreach my $zip ( sort keys(%count) ) {
print "$zip: $count{$zip}\n";
}

Two suggestions:
1. It is best to post a complete, minimal script demonstrating the
problem.
2. This newsgroup is defunct. Try comp.lang.perl.misc in the future.
 
M

Michael Capone

sidel said:
Hello,

I have a csv with name, address, city, state, zip (XXXXX-XXXX). I am hoping
to group all the similiar zip codes and produce a count on each group. My
match so far is m/^\d{5}-\d{4}$/ A match by the first five is ok, but how
would I roll through each one? (for example 90210, 90211, 90213 ...)

thanks
JS

Is this what you're looking for?

open CSVFILE, "my.csv";
while(<CSVFILE>)
{
chomp;
($name, $address, $city, $state, $zip) = split /,/;
$zip =~ m/^(\d{5})-\d{4}$/ ;
$zipcounts{$1}++;
}
close CSVFILE;

foreach $zip (sort keys %zipcounts)
{
print "Zip code $zip has $zipcounts{$zip} entries\n";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top