Search code examples
perlstringstrip

Splitting a changing string with perl


I have a bunch of strings in perl that all look like this:

10 NE HARRISBURG
4 E HASWELL
2 SE OAKLEY
6 SE REDBIRD
PROVO
6 W EADS
21 N HARRISON

What I am needing to do is remove the numbers and the letters from before the city names. The problem I am having is that it varies a lot from city to city. The data is almost never the same. Is it possible to remove this data and keep it in a separate string?


Solution

  • my @l = (
    '10 NE HARRISBURG',
    '4 E HASWELL',
    '2 SE OAKLEY',
    '6 SE REDBIRD',
    'PROVO',
    '6 W EADS',
    '21 N HARRISON',
    );
    
    foreach(@l) {
    

    according to hoobs i changed the regex

        my($beg, $rest) = ($_ =~ /^(\d*\s(?:[NS]|[NS]?[EW])*)?(.*)$/);
        print "beg=$beg \trest=$rest\n";    
    }
    

    output:

    beg=10 NE   rest=HARRISBURG
    beg=4 E     rest=HASWELL
    beg=2 SE    rest=OAKLEY
    beg=6 SE    rest=REDBIRD
    beg=    rest=PROVO
    beg=6 W     rest=EADS
    beg=21 N    rest=HARRISON
    

    for shinjuo, if you want to run only one string you can do :

      my($beg, $rest) = ($l[3] =~ /^(\d*\s(?:[NS]|[NS]?[EW])*)?(.*)$/);
      print "beg=$beg \trest=$rest\n";
    

    and to avoid warning on uninitialized value you have to test if $beg is defined:

    print defined$beg?"beg=$beg\t":"", "rest=$rest\n";