IO::Handle(3perl)
π NAME π
okay bestie, sit down, hydrate π β this is IO::Handle, and its whole job is to supply object methods for I/O handles. that's it. that's the gig. iconic behavior honestly π
this page lives in the Perl Programmers Reference Guide, and it's giving very much "foundational class energy" β¨
β¨ SYNOPSIS β¨
here's the vibe, copy-paste ready, no notes:
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;
and yes, undef $io; automatically closes the file if it's open β it's self-cleaning, we love a low-maintenance queen π§
πΈ DESCRIPTION πΈ
so. IO::Handle is the base class for all other IO handle classes π it is not intended that objects of IO::Handle would be created directly β nope, it's the parent, the blueprint, the main character that everyone else inherits from. several other classes in the IO hierarchy are its descendants, and they get all of its methods for free. periodt.
and listen β if you're reading this because you're looking for a replacement for the FileHandle package, bestie I got you: go read the documentation for IO::File too. like, also. both. π
π CONSTRUCTOR π
new ()β creates a newIO::Handleobject. fresh out the box, no cap π«new_from_fd ( FD, MODE )β creates anIO::Handlelikenewdoes, but it's the deluxe version. it requires two parameters, which are passed to the methodfdopen. if the fdopen fails, the object is destroyed π (rip, doesn't get to exist). otherwise, it is returned to the caller. slay.
π METHODS π
the built-in front-ends
see perlfunc for complete descriptions of each of the following supported IO::Handle methods β heads up, these are just front ends for the corresponding built-in functions:
$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 )
the perlvar-flavored ones
see perlvar for complete descriptions of each of the following supported IO::Handle methods. here's the tea on how they all work π«: all of them return the previous value of the attribute and they take an optional single argument that, when given, will set the value. if no argument is given the previous value is unchanged β except for $io->autoflush, which will actually turn ON autoflush by default π
$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]) $.
not per-filehandle, sorry
the following methods are not supported on a per-filehandle basis. they're class-level, they operate globally, deal with it π
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 for doing normal I/O you might need these π¦
$io->fdopen ( FD, MODE )βfdopenis like an ordinaryopenexcept that its first parameter is not a filename but rather a file handle name, anIO::Handleobject, or a file descriptor number. (for the documentation of theopenmethod, seeIO::File.) it's open, but make it fd-coded β¨$io->openedβ returns true if the object is currently a valid file descriptor, false otherwise. vibe check for your 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. if you use it as the conditional within awhileor C-styleforloop, though, you will need to emulate the functionality of<$io>withdefined($_ = $io->getline). important!! don't skip that part bestie π$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 you accidentally call it in a scalar context π so like, watch the context. it's sensitive.$io->ungetc ( ORD )β pushes a character with the given ordinal value back onto the given handle's input stream. heads up: only one character of pushback per handle is guaranteed β so don't go crazy, you get one (1) undo π$io->write ( BUF, LEN [, OFFSET ] )β thiswriteis somewhat likewritefound in C, in that it is the opposite of read. the wrapper for the perlwritefunction is calledformat_write. however, whilst the Cwritefunction returns the number of bytes written, thiswritefunction simply returns true if successful (likeprint). a more C-likewriteissyswrite(see above). ok so they're different, do not confuse them, I'm begging π«Ά$io->errorβ returns a true value if the given handle has experienced any errors since it was opened or since the last call toclearerr, or if the handle is invalid. it only returns false for a valid handle with no outstanding errors. so like, false is a real compliment here π$io->clearerrβ clear the given handle's error indicator. returns-1if the handle is invalid,0otherwise.$io->syncβsyncsynchronizes a file's in-memory state with that on the physical medium.syncdoes not operate at the perlio api level, but operates on the file descriptor (similar tosysread,sysseekandsystell). 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 theflushmethod.syncis not implemented on all platforms. returns"0 but true"on success,undefon error,undeffor an invalid handle. see fsync(3c). it's giving "I only talk to the fd directly" β¨$io->flushβflushcauses 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,undefon error.$io->printflush ( ARGS )β turns on autoflush, printsARGSand then restores the autoflush status of theIO::Handleobject. returns the return value fromprint. it's a print-and-restore, very polite, we stan a considerate method π$io->blocking ( [ BOOL ] )β if called with an argument,blockingwill turn on non-blocking IO ifBOOLis false, and turn it off ifBOOLis true. (yes, backwards from what you'd expect. it's fine. it's quirky.)
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] )βbinmodesetsbinmodeon the underlyingIOobject, as documented inperldoc -f binmode.binmodeaccepts one optional parameter, which is the layer to be passed on to thebinmodecall.
setbuf / setvbuf π
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: theIO::Handle::setvbuf()is not available by default on Perls 5.8.0 and later becausesetvbuf()is rather specific to using the stdio library, while Perl prefers the new perlio subsystem instead. so like, perlio said "we're not doing that" π
β οΈ WARNING: a variable used as a buffer bysetbuforsetvbufmust not be modified in any way until the IO::Handle is closed orsetbuforsetvbufis 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_IONBFexplicitly. like C,setbufreturns nothing.setvbufreturns"0 but true", on success,undefon failure. bestie. I am not joking about the memory corruption. do not touch the buffer. π«Ά
taint-clean, for the -T and setuid/gid girlies π
lastly, there is a special method for working under -T and setuid/gid 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).
it's literally called "a very trusting action" in the docs. that's canon. don't be naive about your data sources, bestie π
π 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, I propose the 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'. shared space, be respectful, label your stuff β¨
π SEE ALSO π
perlfunc, "I/O Operators" in perlop, IO::File
π 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. yeah. it's a lookalike. catfishing since forever π
π HISTORY π
derived from FileHandle.pm by Graham Barr <gbarr@pobox.com>
and that's the whole page, bestie β you're officially fluent in IO::Handle πβ¨ππ¦πΈπ π«Ά
this little scroll comes from perl v5.44.0, dated 2026-10-17 β go forth and fdopen responsibly, mwah π
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms