Re: Is there a better way than this?

Discussion in 'Perl Misc' started by Charles DeRykus, Jun 4, 2013.

  1. On 6/4/2013 8:07 AM, Dave Stratford wrote:
    > Hi folks,
    >
    > I've got a bit of code, three lines actually, that it seems to me ought to
    > be able to be done far simpler and better, but I can't see how.
    >
    > Background first though.
    >
    > A UK postcode is made up of two parts, outcode and incode. The incode has
    > a standard format: 9AA, that is, it's always three characters long, a
    > digit followed by two letters.
    >
    > The Outcode however, has six possible formats, excluding some odd ones
    > that I know I won't have to worry about: A9, AA9, A99, AA9, A9A and AA9A.
    >
    > My requirements are to extract the initial letter(s) from the outcode. So
    > if a user entered HP13, I want to extract just the HP, equally if they
    > emtered WC1A, I want just the WC.
    >
    > My current code, which works perfectly fine, looks like this:
    >
    > my $oc = substr($outcode,0,2);
    > my $ocr = substr($oc,1,1);
    >
    > $oc = substr($outcode,0,1) if ($ocr =~ /\d/);
    >
    > So take the first two character, then see if the second one is a digit,
    > and if so take just the first character.
    >
    > It works, it just seems to me that it ought to be simpler.
    >


    Another possibility:

    ($oc) = $outcode =~ /^ ([A-Z]+) (?=\d) /ax;


    --
    Charles DeRykus
    Charles DeRykus, Jun 4, 2013
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    1
    Views:
    341
    David Bolen
    Dec 30, 2004
  2. Casey Hawthorne
    Replies:
    0
    Views:
    309
    Casey Hawthorne
    May 12, 2005
  3. Peter Bencsik
    Replies:
    2
    Views:
    823
  4. Neil Shadrach

    Is there a better way than using $+ ?

    Neil Shadrach, Oct 23, 2003, in forum: Perl Misc
    Replies:
    2
    Views:
    72
    Neil Shadrach
    Oct 24, 2003
  5. Replies:
    2
    Views:
    52
    Mark H Harris
    May 13, 2014
Loading...

Share This Page