Process between paragraphs in perl

Discussion in 'Perl Misc' started by Ninja Li, Mar 4, 2010.

  1. Ninja Li

    Ninja Li Guest

    Hi,

    I have a file with the following format, with common words "Sort
    Alphabetically" for each paragraph:

    London|Sort Alphabetically
    line1
    line2
    line3
    Chicago|Sort Alphabetically
    line1
    line2
    Shanghai|Sort Alphabetically
    line1
    line2

    I would like to print the country name after each line under city,
    so the output will be something like:
    London|Sort Alphabetically
    line1 | UK
    line2 | UK
    line3 | UK
    Chicago|Sort Alphabetically
    line1 | US
    line2 | US
    Shanghai|Sort Alphabetically
    line1 | China
    line2 | China

    I tried to split each paragraph into separate file base on "Sort
    Alphabetically" and then merge them again. This is quite tideous. Is
    there an easier way to do this without splitting into separate files?
    The following is some of my code:

    open(INFILE, "<$file");

    foreach $line (<INFILE>)
    {
    if ($line =~ /Alphabetically/)
    {
    my @fields = split(/\|/, $line);
    $location = $fields[0];

    if ($location =~ /London/)
    {
    $location = 'UK';
    }
    elsif ($location =~ /Chicago/)
    {
    $location = 'US';
    }
    elsif ($location =~ /Shanghai/)
    {
    $location = 'China';
    }
    elsif ($location =~ /.../)
    {
    $location = '..';
    }

    close(OUTFILE);
    open(OUTFILE, ">$output$location");
    }
    print OUTFILE $line;
    }
     
    Ninja Li, Mar 4, 2010
    #1
    1. Advertising

  2. Ninja Li

    Ninja Li Guest

    This is a nice solution. Thanks for your help.
     
    Ninja Li, Mar 5, 2010
    #2
    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. Rlrcstr

    Collapsable paragraphs...

    Rlrcstr, May 16, 2005, in forum: ASP .Net
    Replies:
    7
    Views:
    709
    Rlrcstr
    May 17, 2005
  2. jersie0
    Replies:
    0
    Views:
    684
    jersie0
    Nov 23, 2003
  3. Jeff
    Replies:
    3
    Views:
    9,146
    kleinbaas
    Apr 13, 2010
  4. City Dweller

    Default leading for paragraphs

    City Dweller, Apr 6, 2006, in forum: HTML
    Replies:
    13
    Views:
    1,108
    Nije Nego
    Apr 8, 2006
  5. ar

    Numbering paragraphs

    ar, Jun 25, 2003, in forum: XML
    Replies:
    1
    Views:
    3,163
    Marrow
    Jun 25, 2003
Loading...

Share This Page