- Perl ›
- File input/output ›
- here
Disable buffering
Block buffering was very efficient in terms of performance because it stores the output in a write buffer and writes the accumulated amount all at once.
This is unlikely to be a problem when exporting to a local file. The problem arises when communicating with other processes. Perl can use the interprocess communication feature to communicate with other local processes, and the socket feature to communicate with other processes over the network.
If block buffering is performed at this time, it may happen that you intended to send data to the other party but did not send it. It remains in its own write buffer.
One way to solve this is to change block buffering to command buffering. To enable command buffering Predefined variable Set " $| " to 1 To do.
$| = 1;
Example
Below is an example to switch to command buffering.
use strict; use warnings; # File for writing (Note that it will be overwritten) my $file = "example20080812.txt"; open(my $fh, ">", $file) or die "Cannot open $file:$!"; # Change default output handle my $oldfh = select $fh; # Enable command buffering. $| = 1; # Reselect to the original filehandle. select $oldfh; print $fh "Write without delay\n"; print "Written at this point. Size is". -S $file. "Bytes.\n"; sleep 3; close $fh or die "Cannot close $file";
(Reference) sleep function, open function, close function, die function
Command buffering
Perl does not support writing without buffering at all. You don't have to write one character at a time. Instead, you can use command buffering to write when the command print is finished.
It is guaranteed that it will be written to the output before you write the print function and execute following statement.
Command buffering is often used for interactive communication. For example, suppose you send data to someone and wait for a reply. To send data over the network, write to something called a socket (a kind of filehandle) and wait for a reply. At this time, if block buffering is enabled, it means that even if you think that you wrote it, it is actually stored in the write buffer and you are not actually writing it.
Command buffering is used to avoid this.
Code explanation
(1) Enable command buffering
# Change default output handle my $oldfh = select $fh; # Enable command buffering. $| = 1; # Reselect to the original filehandle. select $oldfh;
Command buffering is enabled by setting the predefined variable $| to 1. It should be noted here that the operation for $| is the operation for the "default output destination".
The "default output destination" is the output destination when the file handle is omitted in the print function. The default output destination is STDOUT.
To enable command buffering for writes to $fh, change the "default destination" with the select function, then set the value of $| to 1.
The select function returns the current default output destination, so save it, manipulate $|, and then restore it.