Skyler99 has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I would like to write a program that reads a file finds a number code with a string and takes three previous lines and last line out. Is anybody familiar with HL7 adt messages? The file is an HL7 adt message. It contains specific header string formats like MSH,EVN,PID,FT1, PV1. The code that I need to find is located in FT1. So once I find it, I will need to move out the block that contains this code. for Instance if 123456 is found in FT1 , then I need to remove its MSH, EVN, PID, FT1 & PV1. All these are string lines. I'm looking for suggestions on how to accomplish this task??? Thanks in advance

Replies are listed 'Best First'.
Re: Stripping Lines out of a File
by Thelonius (Priest) on Mar 07, 2003 at 19:45 UTC
    You have to buffer each block. You need to know which segments are part of a block and which start a new block. The code will look something like this:
    #!perl -w my ($fs, $cs, $rs, $ec, $ss); setdelimiters('|^~\&'); sub setdelimiters { ($fs, $cs, $rs, $ec, $ss) = map {quotemeta} split //, $_[0]; } use strict; my $buffer=""; my $suppress = 0; my @field; my %newblock; my %partofblock; # Note: This is just an example. I do not know all segments that star +t a new block $newblock{$_} = 1 for qw(MSH); $partofblock{$_} = 1 for qw(EVN PID PV1 FT1); while (<>) { if (/^(MSH)(.....)/) { setdelimiters($2); } @field = split /$fs/; if ($newblock{$field[0]}) { processbuffer(); } elsif (!$partofblock{$field[0]}) { print STDERR "Possible error: segment=$field[0] line $.\n"; } if ($field[0] eq "FT1") { if ($field[_WHATEVER_] == 123456) { $suppress = 1; } } $buffer .= "$_\n"; } processbuffer(); sub processbuffer { print $buffer unless $suppress; $buffer=""; $suppress = 0; }
Re: Stripping Lines out of a File
by tall_man (Parson) on Mar 07, 2003 at 19:52 UTC
    An alternative that might be simpler to maintain, though more costly to run, is to use Tie::File, which lets you treat a file as an array. You could find the line numbers containing the codes and splice out the appropriate lines.
Re: Stripping Lines out of a File
by steves (Curate) on Mar 07, 2003 at 19:34 UTC

    Without seeing some data I may be off, but the approach I'd take is to gather each block of lines in an array. When you hit the last piece of a block you check for your match condition and conditionally write or don't write the accumulated block to output. Gathering/recognition of blocks is done by matching the tags you give above.