Re: Last line issue



Andrej Kastrin wrote:

John W. Krahn wrote:

This should do what you want:

#!/usr/bin/perl
use warnings;
use strict;

my $FNI = shift;
my $FNO = "$FNI.dat";

open my $OUT, '>', $FNO or die "Cannot open '$FNO' $!";
open my $IN, '<', $FNI or die "Cannot open '$FNI' $!";

my ( $id, $line );
while ( <$IN> ) {
if ( m!<Note>! .. m!</Note>! ) {
( $id, $line ) = ( $1, '' ) if m!<Id>(\d+)</Id>!;
s/\A\s+//;
s/\s+\z//;
tr/\t/ /s; # more efficient than s/\t+/ /g
$line .= $_ if /Id|To|From/;
print $OUT "$id\t$line\n" if m!/Note!;
}
}

close $IN;
close $OUT;

many, many thanks for your quick answer.

I modified your script a bit:
$line .= $_ if /Id|To|From/;
print $OUT "$id\t$line\n" if m!/Note!;

to:
$line .= $_ if m!<Note>! .. m!</Note>!;
print $OUT "$id\t$line\n" if m!</Note>!;


but some problem still persists with the output:
001 <Id>001</Id><To>Thomas</To><From>Joana</From><Message>foo</Message></Note>
002 <Id>002</Id><To>John</To><From>Paula</From><Message>foo</Message></Note>
003 <Id>003</Id><To>Andrew</To><From>Maria</From><Message>foo</Message></Note>

Note that there is no opening <Note> tag at the beginning.

This should work better:

my ( $id, $line );
while ( <$IN> ) {
if ( m!<Note>! .. m!</Note>! ) {
s/\A\s+//;
s/\s+\z//;
tr/\t/ /s;
$id = $1 if m!<Id>(\d+)</Id>!;
if ( m!<Note>! ) {
$line = $_;
}
else {
$line .= $_;
}
print $OUT "$id\t$line\n" if m!/Note!;
}
}



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.



Relevant Pages

  • Re: Random scsi disk disappearing
    ... Such a script exists in the ... New scsi logging level: ... shift 2;; ...
    (Linux-Kernel)
  • Re: Critcize my scripts.
    ... > (I know it's a good practice to put use strict in Perl ... > use strict.The script below work fine if I comment out ... perldoc -f use ... Sub Routines ...
    (perl.beginners)
  • Re: [PATCH] Speed up "make headers_*"
    ... 'use strict' and 'use warnings' is recommended. ... The parentheses are not needed for most of the built-in functions. ... More or less the same comments would apply to the next script as well. ...
    (Linux-Kernel)
  • Re: tricky list comparison problem
    ... > I'm having a bit of an issue with a script I'm working on. ... > - 69078878" as available sectors. ... > use strict(); ... You are telling perl to load the 'strict' module and then you are telling the ...
    (perl.beginners)
  • Re: Regular Expression and file editing.
    ... Goksie wrote: ... If i run the script, the changes could not be effected bcos the files is ... use warnings; ... use strict; ...
    (perl.beginners)