Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: separating every set of textline

by davidj (Priest)
on Mar 02, 2005 at 05:55 UTC ( [id://435707]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://435707]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-03-29 15:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found