in reply to Using the second word in a line to split a file into multiple files

I will demo a "classic way", non-Perl specific way to do this.

You actually have the easiest record parsing case...there is an easily identifiable line that starts a new record and an easily identifiable line that signals the end of the record. This is easier than situations where there is no <EOR> "end of record" and the end of a record is signaled by the start of a new different record.

I used the Perl DATA file handle below, but made a my $fh variable out of it so that filehandle could be passed to a subroutine.
In this algorithm pattern, you loop until you see a start-of-record, then call a subroutine to process that record. The sub returns to the caller and the search for another start-of-record commences.

#!/usr/bin/perl use strict; use warnings; # create a "my $fh data handle" from DATA # in your code, you would open my $fh to an actual # input file my $fh =\*DATA; while (my $line = <$fh>) { process_record ($fh, $line) if ($line =~ /^zone /); } sub process_record { my ($fh, $line) = @_; my ($filename) = $line =~ /^zone\s+(\w+)/; # open a new output file handle to $filename print "would print to a file called $filename\n"; my $record_line; while (defined($record_line =<$fh>) and $record_line !~ /endoffile +/) { print " $record_line"; #you print to outfile #instead of to STDOUT } # optional close of the output file # closes automatically when its $outfh goes out of scope } =prints would print to a file called 2file2 record1a record1b record1c record 1d 2 record empty =cut __DATA__ #comment line => perhaps a version number? one 1file1.nest. 1ss record1a record1b record1c record 1d 2 record empty endoffile zone 2file2.egg. 1ss record1a record1b record1c record 1d 2 record empty endoffile
  • Comment on Re: Using the second word in a line to split a file into multiple files
  • Download Code