IO::Handle(3pm)
π IO::Handle(3pm) β supply object methods for I/O handles π
okay bestie, welcome to the Perl Programmers Reference Guide section for IO::Handle, and no cap this is the glow-up your filehandle game has been waiting for. β¨
πΈ NAME πΈ
IO::Handle β supply object methods for I/O handles π
π SYNOPSIS π
use IO::Handle;
my $io = IO::Handle->new();
if ($io->fdopen(fileno(STDIN),"r")) {
print $io->getline;
$io->close;
}
my $io = IO::Handle->new();
if ($io->fdopen(fileno(STDOUT),"w")) {
$io->print("Some text\n");
}
# setvbuf is not available by default on Perls 5.8.0 and later.
use IO::Handle '_IOLBF';
$io->setvbuf(my $buffer_var, _IOLBF, 1024);
undef $io; # automatically closes the file if it's open
autoflush STDOUT 1;
like, look at that little demo just living its best life π«Ά
π¦ DESCRIPTION π¦
so "IO::Handle" is literally the base class for all the other IO handle classes β it's giving founding mother of the whole friend group π
bestie, you are not supposed to create objects of "IO::Handle" directly. instead, it gets inherited from by several other classes in the IO hierarchy. it's the blueprint, not the building. iykyk ποΈ
and if you're reading this doc because you're looking for a replacement for the "FileHandle" package? okay so real talk: the author suggests you read the documentation for "IO::File" too. do not skip it, it's important fr fr π
β¨ CONSTRUCTOR β¨
new ()β creates a new"IO::Handle"object. fresh out the box, brand new, main character energy πnew_from_fd ( FD, MODE )β creates an"IO::Handle"just likenewdoes. it requires two parameters, which get passed to the method"fdopen". and if the fdopen fails? the object is destroyed π otherwise it gets returned to the caller. gone or given, no in-between π
π₯ METHODS π₯
see perlfunc for the complete descriptions of each of these supported "IO::Handle" methods β they're literally just front ends for the corresponding built-in functions, like a cute little delegation moment:
$io->close
$io->eof
$io->fcntl( FUNCTION, SCALAR )
$io->fileno
$io->format_write( [FORMAT_NAME] )
$io->getc
$io->ioctl( FUNCTION, SCALAR )
$io->read ( BUF, LEN, [OFFSET] )
$io->print ( ARGS )
$io->printf ( FMT, [ARGS] )
$io->say ( ARGS )
$io->stat
$io->sysread ( BUF, LEN, [OFFSET] )
$io->syswrite ( BUF, [LEN, [OFFSET]] )
$io->truncate ( LEN )
and see perlvar for the complete descriptions of each of these supported "IO::Handle" methods. all of them return the previous value of the attribute, and take an optional single argument that β when given β sets the value. if no argument is given the previous value stays unchanged. oh, except $io->autoflush will actually turn ON autoflush by default, she's special like that π
$io->autoflush ( [BOOL] ) $|
$io->format_page_number( [NUM] ) $%
$io->format_lines_per_page( [NUM] ) $=
$io->format_lines_left( [NUM] ) $-
$io->format_name( [STR] ) $~
$io->format_top_name( [STR] ) $^
$io->input_line_number( [NUM]) $.
the following methods are not supported on a per-filehandle basis β so like, no per-handle vibes for these ones, they're global girlies:
IO::Handle->format_line_break_characters( [STR] ) $:
IO::Handle->format_formfeed( [STR]) $^L
IO::Handle->output_field_separator( [STR] ) $,
IO::Handle->output_record_separator( [STR] ) $\
IO::Handle->input_record_separator( [STR] ) $/
and furthermore, for doing normal I/O you might need these:
$io->fdopen ( FD, MODE )β"fdopen"is like an ordinary"open"except its first parameter is not a filename but rather a file handle name, an IO::Handle object, or a file descriptor number. (for the documentation of the"open"method, see IO::File.) π$io->openedβ returns true if the object is currently a valid file descriptor, false otherwise. vibe check on the handle β$io->getlineβ this works like<$io>described in "I/O Operators" in perlop, except that it's more readable and can be safely called in a list context but still returns just one line. however, if used as the conditional within a"while"or C-style"for"loop, you will need to emulate the functionality of<$io>with"defined($_ = $io->getline)". okay that's the sneaky part, write it down π$io->getlinesβ this works like<$io>when called in a list context to read all the remaining lines in a file, except that it's more readable. it will alsocroak()if accidentally called in a scalar context π so like, don't do that$io->ungetc ( ORD )β pushes a character with the given ordinal value back onto the given handle's input stream. only one character of pushback per handle is guaranteed. one (1) character, bestie, don't get greedy π$io->write ( BUF, LEN [, OFFSET ] )β this"write"is somewhat like"write"found in C, in that it is the opposite of read. the wrapper for the perl"write"function is called"format_write". however, whilst the C"write"function returns the number of bytes written, this"write"function simply returns true if successful (like"print"). a more C-like"write"is"syswrite"(see above). okay that's a whole plot twist, stay with me π₯$io->errorβ returns a true value if the given handle has experienced any errors since it was opened or since the last call to"clearerr", or if the handle is invalid. it only returns false for a valid handle with no outstanding errors. so false is literally the best-case scenario π$io->clearerrβ clear the given handle's error indicator. returns-1if the handle is invalid,0otherwise. fresh start energy β¨$io->syncβ"sync"synchronizes a file's in-memory state with that on the physical medium."sync"does not operate at the perlio api level, but operates on the file descriptor (similar to sysread, sysseek and systell). this means that any data held at the perlio api level will not be synchronized. to synchronize data that is buffered at the perlio api level you must use the flush method."sync"is not implemented on all platforms. returns"0 but true"on success,"undef"on error,"undef"for an invalid handle. see fsync(3c). π§ careful bestie, the two levels are not the same thing$io->flushβ"flush"causes perl to flush any buffered data at the perlio api level. any unread data in the buffer will be discarded, and any unwritten data will be written to the underlying file descriptor. returns"0 but true"on success,"undef"on error. π½ iconic behavior honestly$io->printflush ( ARGS )β turns on autoflush, print ARGS and then restores the autoflush status of the"IO::Handle"object. returns the return value from print. a little autoflush cameo, then back to normal π¬$io->blocking ( [ BOOL ] )β if called with an argument,"blocking"will turn on non-blocking IO if"BOOL"is false, and turn it off if"BOOL"is true. (yes, it's inverted, yes it's a little chaotic, love that for us.)
"blocking" will return the value of the previous setting, or the current setting if "BOOL" is not given.
if an error occurs "blocking" will return undef and $! will be set. π€
binmode( [LAYER] )β"binmode"sets"binmode"on the underlying"IO"object, as documented in"perldoc -f binmode".
"binmode" accepts one optional parameter, which is the layer to be passed on to the "binmode" call. π
okay so if the C functions setbuf() and/or setvbuf() are available, then "IO::Handle::setbuf" and "IO::Handle::setvbuf" set the buffering policy for an IO::Handle. the calling sequences for the Perl functions are the same as their C counterparts β including the constants "_IOFBF", "_IOLBF", and "_IONBF" for setvbuf() β except that the buffer parameter specifies a scalar variable to use as a buffer. you should only change the buffer before any I/O, or immediately after calling flush. π«§
WARNING: The IO::Handle::setvbuf() is not available by default on Perls 5.8.0 and later because setvbuf() is rather specific to using the stdio library, while Perl prefers the new perlio subsystem instead. π
WARNING: A variable used as a buffer by"setbuf"or"setvbuf"must not be modified in any way until the IO::Handle is closed or"setbuf"or"setvbuf"is called again, or memory corruption may result! π remember that the order of global destruction is undefined, so even if your buffer variable remains in scope until program termination, it may be undefined before the file IO::Handle is closed. note that you need to import the constants"_IOFBF","_IOLBF", and"_IONBF"explicitly. like C,setbufreturns nothing.setvbufreturns"0 but true", on success,"undef"on failure. bestie this is the serious part, do not touch the buffer, i'm begging π¨
lastly, there's a special method for working under -T and setuid/setgid scripts:
$io->untaintβ marks the object as taint-clean, and as such data read from it will also be considered taint-clean. note that this is a very trusting action to take, and appropriate consideration for the data source and potential vulnerability should be kept in mind. returns0on success,-1if setting the taint-clean flag failed. (eg invalid handle) π so like, trust wisely, queen
π NOTE π
an "IO::Handle" object is a reference to a symbol/GLOB reference (see the Symbol package). some modules that inherit from "IO::Handle" may want to keep object related variables in the hash table part of the GLOB. in an attempt to prevent modules trampling on each other, the author proposes that any such module should prefix its variables with its own name separated by _'s. for example the IO::Socket module keeps a "timeout" variable in 'io_socket_timeout'. see, boundaries! we love boundaries π«Ά
π SEE ALSO π
perlfunc, "I/O Operators" in perlop, IO::File β go read them, they're all in the group chat β¨
π BUGS π
due to backwards compatibility, all filehandles resemble objects of class "IO::Handle", or actually classes derived from that class. they actually aren't. which means you can't derive your own class from "IO::Handle" and inherit those methods. π it's giving "looks like a duck but the inheritance tree said no". not me finding out the hard way fr fr
β HISTORY β
derived from FileHandle.pm by Graham Barr <gbarr@pobox.com> β shoutout to the originator, we appreciate you π
and that's the whole page bestie, slay β¨ this was IO::Handle(3pm) from perl v5.42.3, dated 2026-11-03, brought to you by the Perl Programmers Reference Guide β go forth and handle your I/O with main character energy πππ¦
π¦ where this page comes from
- alpine 3.24: perl-doc 5.42.3-r0 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms