Process between paragraphs in perl

N

Ninja Li

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;
}
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top