6 IO::Handle - supply object methods for I/O handles
13 if ($io->fdopen(fileno(STDIN),"r")) {
19 if ($io->fdopen(fileno(STDOUT),"w")) {
20 $io->print("Some text\n");
23 use IO::Handle '_IOLBF';
24 $io->setvbuf($buffer_var, _IOLBF, 1024);
26 undef $io; # automatically closes the file if it's open
32 C<IO::Handle> is the base class for all other IO handle classes. It is
33 not intended that objects of C<IO::Handle> would be created directly,
34 but instead C<IO::Handle> is inherited from by several other classes
37 If you are reading this documentation, looking for a replacement for
38 the C<FileHandle> package, then I suggest you read the documentation
47 Creates a new C<IO::Handle> object.
49 =item new_from_fd ( FD, MODE )
51 Creates a C<IO::Handle> like C<new> does.
52 It requires two parameters, which are passed to the method C<fdopen>;
53 if the fdopen fails, the object is destroyed. Otherwise, it is returned
60 See L<perlfunc> for complete descriptions of each of the following
61 supported C<IO::Handle> methods, which are just front ends for the
62 corresponding built-in functions:
67 $io->format_write( [FORMAT_NAME] )
69 $io->read ( BUF, LEN, [OFFSET] )
71 $io->printf ( FMT, [ARGS] )
73 $io->sysread ( BUF, LEN, [OFFSET] )
74 $io->syswrite ( BUF, LEN, [OFFSET] )
77 See L<perlvar> for complete descriptions of each of the following
78 supported C<IO::Handle> methods. All of them return the previous
79 value of the attribute and takes an optional single argument that when
80 given will set the value. If no argument is given the previous value
81 is unchanged (except for $io->autoflush will actually turn ON
82 autoflush by default).
84 $io->autoflush ( [BOOL] ) $|
85 $io->format_page_number( [NUM] ) $%
86 $io->format_lines_per_page( [NUM] ) $=
87 $io->format_lines_left( [NUM] ) $-
88 $io->format_name( [STR] ) $~
89 $io->format_top_name( [STR] ) $^
90 $io->input_line_number( [NUM]) $.
92 The following methods are not supported on a per-filehandle basis.
94 IO::Handle->format_line_break_characters( [STR] ) $:
95 IO::Handle->format_formfeed( [STR]) $^L
96 IO::Handle->output_field_separator( [STR] ) $,
97 IO::Handle->output_record_separator( [STR] ) $\
99 IO::Handle->input_record_separator( [STR] ) $/
101 Furthermore, for doing normal I/O you might need these:
105 =item $io->fdopen ( FD, MODE )
107 C<fdopen> is like an ordinary C<open> except that its first parameter
108 is not a filename but rather a file handle name, a IO::Handle object,
109 or a file descriptor number.
113 Returns true if the object is currently a valid file descriptor.
117 This works like <$io> described in L<perlop/"I/O Operators">
118 except that it's more readable and can be safely called in a
119 list context but still returns just one line.
123 This works like <$io> when called in a list context to read all
124 the remaining lines in a file, except that it's more readable.
125 It will also croak() if accidentally called in a scalar context.
127 =item $io->ungetc ( ORD )
129 Pushes a character with the given ordinal value back onto the given
130 handle's input stream. Only one character of pushback per handle is
133 =item $io->write ( BUF, LEN [, OFFSET ] )
135 This C<write> is like C<write> found in C, that is it is the
136 opposite of read. The wrapper for the perl C<write> function is
137 called C<format_write>.
141 Returns a true value if the given handle has experienced any errors
142 since it was opened or since the last call to C<clearerr>.
146 Clear the given handle's error indicator.
150 C<sync> synchronizes a file's in-memory state with that on the
151 physical medium. C<sync> does not operate at the perlio api level, but
152 operates on the file descriptor, this means that any data held at the
153 perlio api level will not be synchronized. To synchronize data that is
154 buffered at the perlio api level you must use the flush method. C<sync>
155 is not implemented on all platforms. See L<fsync(3c)>.
159 C<flush> causes perl to flush any buffered data at the perlio api level.
160 Any unread data in the buffer will be discarded, and any unwritten data
161 will be written to the underlying file descriptor.
163 =item $io->printflush ( ARGS )
165 Turns on autoflush, print ARGS and then restores the autoflush status of the
166 C<IO::Handle> object.
168 =item $io->blocking ( [ BOOL ] )
170 If called with an argument C<blocking> will turn on non-blocking IO if
171 C<BOOL> is false, and turn it off if C<BOOL> is true.
173 C<blocking> will return the value of the previous setting, or the
174 current setting if C<BOOL> is not given.
176 If an error occurs C<blocking> will return undef and C<$!> will be set.
181 If the C functions setbuf() and/or setvbuf() are available, then
182 C<IO::Handle::setbuf> and C<IO::Handle::setvbuf> set the buffering
183 policy for an IO::Handle. The calling sequences for the Perl functions
184 are the same as their C counterparts--including the constants C<_IOFBF>,
185 C<_IOLBF>, and C<_IONBF> for setvbuf()--except that the buffer parameter
186 specifies a scalar variable to use as a buffer. WARNING: A variable
187 used as a buffer by C<setbuf> or C<setvbuf> must not be modified in any
188 way until the IO::Handle is closed or C<setbuf> or C<setvbuf> is called
189 again, or memory corruption may result! Note that you need to import
190 the constants C<_IOFBF>, C<_IOLBF>, and C<_IONBF> explicitly.
192 Lastly, there is a special method for working under B<-T> and setuid/gid
199 Marks the object as taint-clean, and as such data read from it will also
200 be considered taint-clean. Note that this is a very trusting action to
201 take, and appropriate consideration for the data source and potential
202 vulnerability should be kept in mind.
208 A C<IO::Handle> object is a reference to a symbol/GLOB reference (see
209 the C<Symbol> package). Some modules that
210 inherit from C<IO::Handle> may want to keep object related variables
211 in the hash table part of the GLOB. In an attempt to prevent modules
212 trampling on each other I propose the that any such module should prefix
213 its variables with its own name separated by _'s. For example the IO::Socket
214 module keeps a C<timeout> variable in 'io_socket_timeout'.
219 L<perlop/"I/O Operators">,
224 Due to backwards compatibility, all filehandles resemble objects
225 of class C<IO::Handle>, or actually classes derived from that class.
226 They actually aren't. Which means you can't derive your own
227 class from C<IO::Handle> and inherit those methods.
231 Derived from FileHandle.pm by Graham Barr E<lt>F<gbarr@pobox.com>E<gt>
237 our($VERSION, @EXPORT_OK, @ISA);
241 use IO (); # Load the XS module
250 output_field_separator
251 output_record_separator
252 input_record_separator
255 format_lines_per_page
259 format_line_break_characters
279 ################################################
280 ## Constructors, destructors.
284 my $class = ref($_[0]) || $_[0] || "IO::Handle";
285 @_ == 1 or croak "usage: new $class";
291 my $class = ref($_[0]) || $_[0] || "IO::Handle";
292 @_ == 3 or croak "usage: new_from_fd $class FD, MODE";
295 IO::Handle::fdopen($io, @_)
301 # There is no need for DESTROY to do anything, because when the
302 # last reference to an IO object is gone, Perl automatically
303 # closes its associated files (if any). However, to avoid any
304 # attempts to autoload DESTROY, we here define it to do nothing.
309 ################################################
313 sub _open_mode_string {
315 $mode =~ /^\+?(<|>>?)$/
316 or $mode =~ s/^r(\+?)$/$1</
317 or $mode =~ s/^w(\+?)$/$1>/
318 or $mode =~ s/^a(\+?)$/$1>>/
319 or croak "IO::Handle: bad open mode: $mode";
324 @_ == 3 or croak 'usage: $io->fdopen(FD, MODE)';
325 my ($io, $fd, $mode) = @_;
328 if (ref($fd) && "".$fd =~ /GLOB\(/o) {
329 # It's a glob reference; Alias it as we cannot get name of anon GLOBs
330 my $n = qualify(*GLOB);
333 } elsif ($fd =~ m#^\d+$#) {
334 # It's an FD number; prefix with "=".
338 open($io, _open_mode_string($mode) . '&' . $fd)
343 @_ == 1 or croak 'usage: $io->close()';
349 ################################################
350 ## Normal I/O functions.
357 @_ == 1 or croak 'usage: $io->opened()';
358 defined fileno($_[0]);
362 @_ == 1 or croak 'usage: $io->fileno()';
367 @_ == 1 or croak 'usage: $io->getc()';
372 @_ == 1 or croak 'usage: $io->eof()';
377 @_ or croak 'usage: $io->print(ARGS)';
383 @_ >= 2 or croak 'usage: $io->printf(FMT,[ARGS])';
389 @_ == 1 or croak 'usage: $io->getline()';
391 return scalar <$this>;
394 *gets = \&getline; # deprecated
397 @_ == 1 or croak 'usage: $io->getlines()';
399 croak 'Can\'t call $io->getlines in a scalar context, use $io->getline';
405 @_ == 2 or croak 'usage: $io->truncate(LEN)';
406 truncate($_[0], $_[1]);
410 @_ == 3 || @_ == 4 or croak 'usage: $io->read(BUF, LEN [, OFFSET])';
411 read($_[0], $_[1], $_[2], $_[3] || 0);
415 @_ == 3 || @_ == 4 or croak 'usage: $io->sysread(BUF, LEN [, OFFSET])';
416 sysread($_[0], $_[1], $_[2], $_[3] || 0);
420 @_ >= 2 && @_ <= 4 or croak 'usage: $io->write(BUF [, LEN [, OFFSET]])';
422 $_[2] = length($_[1]) unless defined $_[2];
423 print { $_[0] } substr($_[1], $_[3] || 0, $_[2]);
427 @_ >= 2 && @_ <= 4 or croak 'usage: $io->syswrite(BUF [, LEN [, OFFSET]])';
428 $_[2] = length($_[1]) unless defined $_[2];
429 syswrite($_[0], $_[1], $_[2], $_[3] || 0);
433 @_ == 1 or croak 'usage: $io->stat()';
437 ################################################
438 ## State modification functions.
442 my $old = new SelectSaver qualify($_[0], caller);
444 $| = @_ > 1 ? $_[1] : 1;
448 sub output_field_separator {
449 carp "output_field_separator is not supported on a per-handle basis"
452 $, = $_[1] if @_ > 1;
456 sub output_record_separator {
457 carp "output_record_separator is not supported on a per-handle basis"
460 $\ = $_[1] if @_ > 1;
464 sub input_record_separator {
465 carp "input_record_separator is not supported on a per-handle basis"
468 $/ = $_[1] if @_ > 1;
472 sub input_line_number {
474 my $tell = tell qualify($_[0], caller) if ref($_[0]);
476 $. = $_[1] if @_ > 1;
480 sub format_page_number {
481 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
483 $% = $_[1] if @_ > 1;
487 sub format_lines_per_page {
488 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
490 $= = $_[1] if @_ > 1;
494 sub format_lines_left {
495 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
497 $- = $_[1] if @_ > 1;
502 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
504 $~ = qualify($_[1], caller) if @_ > 1;
508 sub format_top_name {
509 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
511 $^ = qualify($_[1], caller) if @_ > 1;
515 sub format_line_break_characters {
516 carp "format_line_break_characters is not supported on a per-handle basis"
519 $: = $_[1] if @_ > 1;
523 sub format_formfeed {
524 carp "format_formfeed is not supported on a per-handle basis"
527 $^L = $_[1] if @_ > 1;
536 formline($picture, @_);
541 @_ < 3 || croak 'usage: $io->write( [FORMAT_NAME] )';
544 my $oldfmt = $io->format_name($fmt);
546 $io->format_name($oldfmt);
554 @_ == 3 || croak 'usage: $io->fcntl( OP, VALUE );';
556 return fcntl($io, $op, $_[2]);
561 @_ == 3 || croak 'usage: $io->ioctl( OP, VALUE );';
563 return ioctl($io, $op, $_[2]);
566 # this sub is for compatability with older releases of IO that used
567 # a sub called constant to detemine if a constant existed -- GMB
569 # The SEEK_* and _IO?BF constants were the only constants at that time
570 # any new code should just chech defined(&CONSTANT_NAME)
575 (($name =~ /^(SEEK_(SET|CUR|END)|_IO[FLN]BF)$/) && defined &{$name})
576 ? &{$name}() : undef;
580 # so that flush.pl can be depriciated
584 my $old = new SelectSaver qualify($io, caller) if ref($io);