develooper Front page | perl.beginners | Postings from March 2002

Re: Newbie question

Thread Previous | Thread Next
Eric Beaudoin
March 3, 2002 18:32
Re: Newbie question
Message ID:
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?
>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})/;


(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               <>

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About