D
denis.papathanasiou
I have a script which reads a plain text (dos) file line-by-line and
splits it into several smaller files, based on a single attribute.
The code (below) works, except when a line is malformed (i.e., the
line contains binary or control characters), and the script just exits
with an error:
open(IN, "$IN_FILE") or die "\n\terror: Could not read $IN_FILE $!
\n"; ;
binmode(IN);
while( $ln=<IN> ) {
if( $ln =~ m/\r\n$/ ) {
$ln =~ s/\r\n$/\n/; # dos2unix: convert CR LF to LF
if( $. > 0 ) { # skip the header line
$sym = substr($ln, 10, 16);
$sym =~ s/ //g;
if( $prior_sym ne $sym ) {
if( $prior_sym ne '' ) { close(OUT); }
$sym_file = $OUT_PATH . "/" . $sym . "." . $OUT_SUFFIX ;
open(OUT, ">$sym_file") or die "\n\terror: Could not write to
$sym_file $!\n";
binmode(OUT);
}
print OUT $ln;
$prior_sym = $sym ;
}
}
}
close(IN);
What I'd like it to do, instead, is if it hits a bad line, write a
warning and keep going to the end of the file.
I've tried wrapping the block above in "eval { }; warn $@ if $@;" but
that doesn't trap the error; even with eval/warn, a bad line will
cause the script to exit.
Is there a better way of doing this?
splits it into several smaller files, based on a single attribute.
The code (below) works, except when a line is malformed (i.e., the
line contains binary or control characters), and the script just exits
with an error:
open(IN, "$IN_FILE") or die "\n\terror: Could not read $IN_FILE $!
\n"; ;
binmode(IN);
while( $ln=<IN> ) {
if( $ln =~ m/\r\n$/ ) {
$ln =~ s/\r\n$/\n/; # dos2unix: convert CR LF to LF
if( $. > 0 ) { # skip the header line
$sym = substr($ln, 10, 16);
$sym =~ s/ //g;
if( $prior_sym ne $sym ) {
if( $prior_sym ne '' ) { close(OUT); }
$sym_file = $OUT_PATH . "/" . $sym . "." . $OUT_SUFFIX ;
open(OUT, ">$sym_file") or die "\n\terror: Could not write to
$sym_file $!\n";
binmode(OUT);
}
print OUT $ln;
$prior_sym = $sym ;
}
}
}
close(IN);
What I'd like it to do, instead, is if it hits a bad line, write a
warning and keep going to the end of the file.
I've tried wrapping the block above in "eval { }; warn $@ if $@;" but
that doesn't trap the error; even with eval/warn, a bad line will
cause the script to exit.
Is there a better way of doing this?