in reply to separating every set of textline

Note that what follows is pretty much a hack, but it might get you started. What it does is
1) grab everything from the line containing the string CITY to the line containing the string FLORIDA (I am assuming that FLORIDA is a header).
2) grabs the first word after CITY and opens it as a text file
3) writes all the lines grabbed as indicated above and prints them to the file.

#!/usr/bin/perl use strict; my ($file); open(FILE, "<file.txt"); while(<FILE>) { chomp($_); if(/CITY/ ... /FLORIDA/) { if( ($file) = $_ =~ m/.+CITY:\s+(\w+)\s+/ ) { close(FH); $file .= '.txt'; open(FH, ">>$file"); } print FH "$_\n" unless $_ =~ m/FLORIDA/; } } close(FILE);
hope this helps,
davidj

Replies are listed 'Best First'.
Re^2: separating every set of textline
by deibyz (Hermit) on Mar 02, 2005 at 10:25 UTC
    Only note that if the file is big, and there is not a lot of different files to create, calling open everytime a file must be update can be a considerable overhead (I've been in the same situation just a few days before).

    If the different files can be determinated before the loop, you can open all of them and the use the apropiate (i.e., keeping them in a hash). When they're not known until runtime (it was my case), I used a closure returning lexical filehandles from a hash. Something like that:

    { my %handles; # Closure keeps the hash between function calls sub handle{ my $city = shift; my $temp; unless ($handles{$city}){ open $temp, ">", "$city.txt" or die "$!"; $handles{$city} = $temp; } return $handles{$city}; } }

    It worked for me and reduced the execution time about a 50%. Hope it helps.