user1690130
user1690130

Reputation: 500

Buffering an output file

I have an output file that gets created in my perl script. I'd like for all of the information to get outputted at once rather than gradually. This would be done via buffering? How would this work?

The relevant lines of code are:

 open( my $o,  '>', 'output.txt' ) or die "Can't open output.txt: $!";

 (then later on)
 print( $o ("$id"),"\n" );

 (then later on)
 close $o;

Upvotes: 2

Views: 288

Answers (2)

friedo
friedo

Reputation: 66957

You want to turn buffering off in order to make sure everything is printed at once. The old-fashioned way involved messing around with the special $| variable directly, but a better way is to use IO::File, which hides the details.

use IO::File;

open my $o, '>', 'output.txt' or die "Can't open output.txt: $!";
$o->autoflush( 1 );
$o->print( $id );

Upvotes: 2

James Green
James Green

Reputation: 1753

Perl actually buffers its output by default -- you can switch this off by setting the special variable $|.

If you really want all your output at once, the safest bet is to just not send it for output until you're ready, e.g.:

use IO::Handle qw( );  # Not necessary in newer versions of Perl.

my @output;

(then later on)
push @output, $id;

(then later on)
open( my $o,  '>', 'output.txt' ) or die "Can't open output.txt: $!";
$o->autoflush(1); # Disable buffering now since we really do want the output.
                  #   This is optional since we immediately call close.
print( $o map "$_\n", @output );
close $o;

Upvotes: 2

Related Questions