Front page | perl.beginners |
Postings from March 2002
Re: Newbie question
Thread Previous
|
Thread Next
From:
Eric Beaudoin
Date:
March 3, 2002 18:32
Subject:
Re: Newbie question
Message ID:
5.1.0.14.2.20020303212017.00a97420@pop.videotron.ca
At 21:15 2002.03.03, suraj rajendran wrote:
>Here is a very basic question:
>I am trying to print only the zip code of massachusets
>Even though this works, i am pretty sure there is a
>better way doing this. Any ideas?
>
>#!/usr/bin/perl
>while (<DATA>) {
>($name, $phone, $address, $dob, $salary) = split(":",
>$_);
>($add1, $city, $statezip) = split(",",$address);
>($state, $zip) = split(' ',$statezip);
>print "$zip\n" if $statezip =~/MA/;
>
>}
I don't think you need all those variable. split return a list and you can always access a list element by using it's position in the list. So
use strict;
use warnings;
while(<DATA>) {
print "$1\n" if (split(/,/,(split(/:/,$_))[2]))[2] =~ /MA\s(\d{5})/;
}
__DATA__
....
(split(/:/,$_))[2] returns the third element of you split
(split(/,/,(split(/:/,$_))[2]))[2] returns third element of a the third element
The regex does
/MA # Match MA for massachusets
\s # Match one white space
(\d{5}) # Match 5 digits and put the result in $1 if matched
/x # x would need to be used in order to put comments
# in the regex
But then, your solution was more readable and you might want to do something with the other pieces of the address.
Hope this helps
----------------------------------------------------------
Éric Beaudoin <mailto:beaudoer@videotron.ca>
Thread Previous
|
Thread Next