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

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to