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

#!/usr/bin/perl while(<DATA>){ chomp; if(/^\.\.(.*):$/) { $fh = output($output, $tag, $fh); $output = ""; $tag = $1; } $fh = output($output, $tag, $fh); } sub output { my ($output, $tag, $fh) = @_; if($output) { if($output =~ m/\.\.DN:(.*)/) { if($fh) { close($fh); } open($fh, '>', "$1.xml") or die "$1.xml: $!"; print $fh "$output"; } } return($fh); } # End of sub sroutine __DATA__ ..DN: 000044255 ..CB: ..SN: D046H6J5 ..PD: 20091030 ..DD: Friday, October 30, 2009 ..PY: 2009 ..ED: ..DN: 000044254 ..CB: ..SN: D046H6IR ..PD: 20091030 ..DD: Friday, October 30, 2009 ..PY: 2009 ..ED:
How to split the file until the line matches another ..DN:
I tried to split the file but no luck.The filename is the value of ..DN:

Replies are listed 'Best First'.
Re: Split file
by BioLion (Curate) on Nov 09, 2009 at 17:42 UTC
      #!/usr/bin/perl $/ = '..DN'; while(<DATA>){ chomp; if($output =~ m/\.\.DN:(.*)/) { open($fh, '>', "$1.xml") or die "$1.xml: $!"; print $fh, $_; } # End of sub sroutine }
Re: Split file
by bichonfrise74 (Vicar) on Nov 09, 2009 at 18:03 UTC
    You can try something like this.
    #!/usr/bin/perl use strict; while (<DATA>) { if (/\.\.DN:\n/ ... /(\w+)\n/ ) { print "$1\n" if $1; } } __DATA__ ..DN: 000044255 ..CB: ..SN: D046H6J5 ..PD: 20091030 ..DD: Friday, October 30, 2009 ..PY: 2009 ..ED: ..DN: 000044254 ..CB: ..SN: D046H6IR ..PD: 20091030 ..DD: Friday, October 30, 2009 ..PY: 2009 ..ED:
Re: Split file
by arun_kom (Monk) on Nov 09, 2009 at 20:39 UTC

    Assuming that your data file always begins with a matching pattern on the first line as in the sample data you provided, the following would work.

    use strict; use warnings; while(<DATA>){ if(/DN:$/){ chomp(my $filename = <DATA>); open FH, '>', $filename or die; } else { print FH $_; } }