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 new IO::Handle object. fresh out the box, no cap πŸ’«
  • new_from_fd ( FD, MODE ) β€” creates an IO::Handle like new does, but it's the deluxe version. it requires two parameters, which are passed to the method fdopen. 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 ) β€” fdopen is like an ordinary open except that 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.) 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 a while or C-style for loop, though, you will need to emulate the functionality of <$io> with defined($_ = $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 also croak() 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 ] ) β€” 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). 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 to clearerr, 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 -1 if the handle is invalid, 0 otherwise.
  • $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). it's giving "I only talk to the fd directly" ✨
  • $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.
  • $io->printflush ( ARGS ) β€” turns on autoflush, prints ARGS and then restores the autoflush status of the IO::Handle object. returns the return value from print. it's a print-and-restore, very polite, we stan a considerate method πŸŽ€
  • $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, 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] ) β€” 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.

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: 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. so like, perlio said "we're not doing that" πŸ’…
⚠️ 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, setbuf returns nothing. setvbuf returns "0 but true", on success, undef on 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. returns 0 on success, -1 if 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