in reply to File read and re-ordering
Let's see if I can do something while I read your specification.
# "What I essentially need is a way to say..." my $start_tag = 'BEGIN'; my $end_constant = 'END'; my $headerformat = join('; ', "%s=%s" x 17)."\n"; # XXX ? format for +printf() ? my $headerfile = 'header000'; my $detailsection = 'detail000'; open IN, '<', $file) or die "Can't read '$file': $!\n"; RECORD: while(defined($_ = <IN>)) { my %out; # we'll capture the "record content" for pr +intf() here if (/$start_tag/) { # "...start at this character..." $. = 0; # reset line counter while(<IN>) { # "...read each line for the next 17..." # XXX the specs aren't clear he +r. my ($key, $value) = split; # so I'll just split $out{$key} = $value; # "...assign to values to do # a printf statement..." if($. == 17) { # done with reading the record. do "the pri +ntf()" open HEADER, '>', $headerfile or die "Can't write to '$headerfile': $!\n"; printf HEADER $headerformat, map { $_,$out{$_} } keys +%out; close HEADER; $headerfile++; # string increment: header000 -> he +ader001 $. = 0; open DETAIL, '>', $detailsection or die "Can't write to '$detailsection': $!\n"; # "starting at the 18th line of tha +t record..." while(<IN>) { # "...read until the end constant.. +." print DETAIL; # "...and print that straight to # a different file..." last if /$end_constant/; } close DETAIL; $detailsection++; next RECORD; # "...and then start the entire l +oop again." } } } }
Poo. That might work, but it's butt ugly and hard to read. Let's refactor that a bit.
open my $fh, '<', $file) or die "Can't read '$file': $!\n"; while(<$fh>) { write_record($fh,$headerfile) if /$start_tag/; $headerfile++; } sub write_record { my ($fh, $outfile) = @_; my %out; $. = 0; while(<$fh>) { my ($key, $value) = split; $out{$key} = $value; if ($. == 17) { open my $header, '>', $outfile or die "Can't write '$outfile': $!\n"; printf $header $headerformat, map { $_,$out{$_} } keys %ou +t; close $header; write_detail($fh,$detailsection); $detailsection++; return; } } } sub write_detail { my ($fh, $detailfile) = @_; open my $detail, '>', $detailfile or die "Can't write to '$detailfile': $!\n"; while(<$fh>) { last if /$end_constant/; print $detail; } close $detail; }
Does that make sense to you? If it doesn't, write better specifications ;-)
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
|
|---|