Perl does not support truly unbuffered output (except insofar as you can syswrite(OUT, $char, 1)), although it does support is "command buffering", in which a physical write is performed after every output command.
The C standard I/O library (stdio) normally buffers characters sent to devices so that there isn't a system call for each byte. In most stdio implementations, the type of output buffering and the size of the buffer varies according to the type of device. Perl's print() and write() functions normally buffer output, while syswrite() bypasses buffering all together.
If you want your output to be sent immediately when you execute print() or write() (for instance, for some network protocols), you must set the handle's autoflush flag. This flag is the Perl variable $| and when it is set to a true value, Perl will flush the handle's buffer after each print() or write(). Setting $| affects buffering only for the currently selected default filehandle. You choose this handle with the one argument select() call (see $| in perlvar and select in perlfunc).
Use select() to choose the desired handle, then set its per-filehandle variables.
$old_fh = select(OUTPUT_HANDLE);
$| = 1;
select($old_fh);
Some modules offer object-oriented access to handles and their variables, although they may be overkill if this is the only thing you do with them. You can use IO::Handle:
use IO::Handle;
open my( $printer ), ">", "/dev/printer"); # but is this?
$printer->autoflush(1);
or IO::Socket (which inherits from IO::Handle):
use IO::Socket; # this one is kinda a pipe?
my $sock = IO::Socket::INET->new( 'www.example.com:80' );
$sock->autoflush();
You can also flush an IO::Handle object without setting autoflush. Call the flush method to flush the buffer yourself:
use IO::Handle;
open my( $printer ), ">", "/dev/printer");
$printer->flush; # one time flush
Saturday, September 22, 2007
What is Perl?
Perl is a high-level programming language with an eclectic heritage written by Larry Wall and a cast of thousands. It derives from the ubiquitous C programming language and to a lesser extent from sed, awk, the Unix shell, and at least a dozen other tools and languages. Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, graphical programming, networking, and world wide web programming. These strengths make it especially popular with system administrators and CGI script authors, but mathematicians, geneticists, journalists, and even managers also use Perl. Maybe you should, too.
Subscribe to:
Posts (Atom)