in reply to Ugly variable-length record handling

I've had to put up with that sort of loop lots of times -- yes, it has a klugy feel to it, but it still seems easier, simpler, clearer, etc, than alternatives, so I just live with it.

Other things can be done in general to streamline your code a little bit -- fewer variables, fewer lines of code, less open/close overhead on the temp file:

open( DAT, '<', 'export.dat' ) or die "Open for read failed on export.dat: $!"; my $tmp; # file handle while ( <DAT> ) { next unless ( /\S/ ); if ( /^1/ ) { if ( defined( $tmp )) { output_data( $tmp ); } open( $tmp, '+>', 'export.tmp' ) # open read/write, truncate +first or die "Open failed for export.tmp: $!"; } print $tmp $_; } output_data( $tmp ); sub output_data { my $fh = shift; seek( $fh, 0, 0 ); # rewind to start of file # do stuff with export.tmp contents... close $fh; }

Replies are listed 'Best First'.
Re^2: Ugly variable-length record handling
by Melly (Chaplain) on Jan 04, 2007 at 09:58 UTC

    Thanks all - some nice variations... but I'll probably stick with the original (IIABDFI) - that said, here's a 'nicer' version I came up with (which uses a two-element array, plus a push and a shift), but I suspect that the niceness comes at the expense of readability...

    use strict; open(DAT, "export.dat")||die "Cannot open export.dat for read:$!\n"; my @temp_lines; push @temp_lines, scalar <DAT>; my $closed = 1; while($temp_lines[0] !~ /^<EOF>$/){ open(TEMP, ">temp.dat") if $closed; $closed = 0; push @temp_lines, (eof DAT) ? '<EOF>' : (scalar <DAT>) ; print TEMP shift @temp_lines; if($temp_lines[0] =~ /^(1|<EOF>)/){ close TEMP; &output_data(); $closed = 1; } } close DAT; sub output_data{ print "in output_data\n"; open(TEST, 'temp.dat')||die "cannot open temp in sub:$!\n"; while(<TEST>){ chomp; print "$_\n" if $_ =~ /\S/; } print "end of output_data\n"; }
    map{$a=1-$_/10;map{$d=$a;$e=$b=$_/20-2;map{($d,$e)=(2*$d*$e+$a,$e**2 -$d**2+$b);$c=$d**2+$e**2>4?$d=8:_}1..50;print$c}0..59;print$/}0..20
    Tom Melly, pm@tomandlu.co.uk