SYN SYN
[p5sagit/p5-mst-13.2.git] / ext / IO / lib / IO / Handle.pm
CommitLineData
774d564b 1
8add82fc 2package IO::Handle;
3
4=head1 NAME
5
27d4819a 6IO::Handle - supply object methods for I/O handles
8add82fc 7
8=head1 SYNOPSIS
9
10 use IO::Handle;
11
cf7fe8a2 12 $io = new IO::Handle;
13 if ($io->fdopen(fileno(STDIN),"r")) {
14 print $io->getline;
15 $io->close;
8add82fc 16 }
17
cf7fe8a2 18 $io = new IO::Handle;
19 if ($io->fdopen(fileno(STDOUT),"w")) {
20 $io->print("Some text\n");
8add82fc 21 }
22
3370baa8 23 use IO::Handle '_IOLBF';
cf7fe8a2 24 $io->setvbuf($buffer_var, _IOLBF, 1024);
8add82fc 25
cf7fe8a2 26 undef $io; # automatically closes the file if it's open
774d564b 27
8add82fc 28 autoflush STDOUT 1;
29
30=head1 DESCRIPTION
31
774d564b 32C<IO::Handle> is the base class for all other IO handle classes. It is
33not intended that objects of C<IO::Handle> would be created directly,
34but instead C<IO::Handle> is inherited from by several other classes
35in the IO hierarchy.
36
37If you are reading this documentation, looking for a replacement for
38the C<FileHandle> package, then I suggest you read the documentation
cf7fe8a2 39for C<IO::File> too.
8add82fc 40
27d4819a 41=head1 CONSTRUCTOR
42
43=over 4
44
45=item new ()
8add82fc 46
27d4819a 47Creates a new C<IO::Handle> object.
8add82fc 48
27d4819a 49=item new_from_fd ( FD, MODE )
50
51Creates a C<IO::Handle> like C<new> does.
52It requires two parameters, which are passed to the method C<fdopen>;
53if the fdopen fails, the object is destroyed. Otherwise, it is returned
54to the caller.
55
56=back
57
58=head1 METHODS
8add82fc 59
8add82fc 60See L<perlfunc> for complete descriptions of each of the following
61supported C<IO::Handle> methods, which are just front ends for the
62corresponding built-in functions:
a6006777 63
cf7fe8a2 64 $io->close
65 $io->eof
66 $io->fileno
67 $io->format_write( [FORMAT_NAME] )
68 $io->getc
69 $io->read ( BUF, LEN, [OFFSET] )
70 $io->print ( ARGS )
71 $io->printf ( FMT, [ARGS] )
72 $io->stat
73 $io->sysread ( BUF, LEN, [OFFSET] )
22d4bb9c 74 $io->syswrite ( BUF, [LEN, [OFFSET]] )
cf7fe8a2 75 $io->truncate ( LEN )
8add82fc 76
77See L<perlvar> for complete descriptions of each of the following
cf7fe8a2 78supported C<IO::Handle> methods. All of them return the previous
79value of the attribute and takes an optional single argument that when
80given will set the value. If no argument is given the previous value
81is unchanged (except for $io->autoflush will actually turn ON
82autoflush by default).
8add82fc 83
cf7fe8a2 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]) $.
91
92The following methods are not supported on a per-filehandle basis.
93
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] ) $\
98
99 IO::Handle->input_record_separator( [STR] ) $/
8add82fc 100
101Furthermore, for doing normal I/O you might need these:
102
103=over
104
cf7fe8a2 105=item $io->fdopen ( FD, MODE )
948ecc40 106
107C<fdopen> is like an ordinary C<open> except that its first parameter
108is not a filename but rather a file handle name, a IO::Handle object,
109or a file descriptor number.
110
cf7fe8a2 111=item $io->opened
948ecc40 112
113Returns true if the object is currently a valid file descriptor.
114
cf7fe8a2 115=item $io->getline
8add82fc 116
cf7fe8a2 117This works like <$io> described in L<perlop/"I/O Operators">
22d4bb9c 118except that it's more readable and can be safely called in a
119list context but still returns just one line.
8add82fc 120
cf7fe8a2 121=item $io->getlines
8add82fc 122
22d4bb9c 123This works like <$io> when called in a list context to read all
124the remaining lines in a file, except that it's more readable.
8add82fc 125It will also croak() if accidentally called in a scalar context.
126
cf7fe8a2 127=item $io->ungetc ( ORD )
27d4819a 128
948ecc40 129Pushes a character with the given ordinal value back onto the given
cf7fe8a2 130handle's input stream. Only one character of pushback per handle is
131guaranteed.
27d4819a 132
cf7fe8a2 133=item $io->write ( BUF, LEN [, OFFSET ] )
27d4819a 134
948ecc40 135This C<write> is like C<write> found in C, that is it is the
27d4819a 136opposite of read. The wrapper for the perl C<write> function is
137called C<format_write>.
138
cf7fe8a2 139=item $io->error
948ecc40 140
141Returns a true value if the given handle has experienced any errors
142since it was opened or since the last call to C<clearerr>.
143
cf7fe8a2 144=item $io->clearerr
948ecc40 145
146Clear the given handle's error indicator.
27d4819a 147
cf7fe8a2 148=item $io->sync
149
150C<sync> synchronizes a file's in-memory state with that on the
151physical medium. C<sync> does not operate at the perlio api level, but
152operates on the file descriptor, this means that any data held at the
153perlio api level will not be synchronized. To synchronize data that is
154buffered at the perlio api level you must use the flush method. C<sync>
155is not implemented on all platforms. See L<fsync(3c)>.
156
157=item $io->flush
158
159C<flush> causes perl to flush any buffered data at the perlio api level.
160Any unread data in the buffer will be discarded, and any unwritten data
161will be written to the underlying file descriptor.
162
163=item $io->printflush ( ARGS )
164
165Turns on autoflush, print ARGS and then restores the autoflush status of the
166C<IO::Handle> object.
167
168=item $io->blocking ( [ BOOL ] )
169
170If called with an argument C<blocking> will turn on non-blocking IO if
171C<BOOL> is false, and turn it off if C<BOOL> is true.
172
173C<blocking> will return the value of the previous setting, or the
174current setting if C<BOOL> is not given.
175
176If an error occurs C<blocking> will return undef and C<$!> will be set.
177
8add82fc 178=back
179
cf7fe8a2 180
948ecc40 181If the C functions setbuf() and/or setvbuf() are available, then
182C<IO::Handle::setbuf> and C<IO::Handle::setvbuf> set the buffering
183policy for an IO::Handle. The calling sequences for the Perl functions
184are the same as their C counterparts--including the constants C<_IOFBF>,
185C<_IOLBF>, and C<_IONBF> for setvbuf()--except that the buffer parameter
186specifies a scalar variable to use as a buffer. WARNING: A variable
187used as a buffer by C<setbuf> or C<setvbuf> must not be modified in any
188way until the IO::Handle is closed or C<setbuf> or C<setvbuf> is called
cf7fe8a2 189again, or memory corruption may result! Note that you need to import
3370baa8 190the constants C<_IOFBF>, C<_IOLBF>, and C<_IONBF> explicitly.
948ecc40 191
192Lastly, there is a special method for working under B<-T> and setuid/gid
193scripts:
515e7bd7 194
195=over
196
cf7fe8a2 197=item $io->untaint
515e7bd7 198
199Marks the object as taint-clean, and as such data read from it will also
200be considered taint-clean. Note that this is a very trusting action to
201take, and appropriate consideration for the data source and potential
202vulnerability should be kept in mind.
203
204=back
205
27d4819a 206=head1 NOTE
8add82fc 207
cf7fe8a2 208A C<IO::Handle> object is a reference to a symbol/GLOB reference (see
209the C<Symbol> package). Some modules that
8add82fc 210inherit from C<IO::Handle> may want to keep object related variables
211in the hash table part of the GLOB. In an attempt to prevent modules
212trampling on each other I propose the that any such module should prefix
213its variables with its own name separated by _'s. For example the IO::Socket
214module keeps a C<timeout> variable in 'io_socket_timeout'.
215
216=head1 SEE ALSO
217
218L<perlfunc>,
219L<perlop/"I/O Operators">,
774d564b 220L<IO::File>
8add82fc 221
222=head1 BUGS
223
224Due to backwards compatibility, all filehandles resemble objects
225of class C<IO::Handle>, or actually classes derived from that class.
226They actually aren't. Which means you can't derive your own
227class from C<IO::Handle> and inherit those methods.
228
229=head1 HISTORY
230
cf7fe8a2 231Derived from FileHandle.pm by Graham Barr E<lt>F<gbarr@pobox.com>E<gt>
8add82fc 232
233=cut
234
cb50131a 235require 5.005_64;
7a4c00b4 236use strict;
cb50131a 237our($VERSION, @EXPORT_OK, @ISA);
8add82fc 238use Carp;
239use Symbol;
240use SelectSaver;
cf7fe8a2 241use IO (); # Load the XS module
8add82fc 242
243require Exporter;
244@ISA = qw(Exporter);
245
cf7fe8a2 246$VERSION = "1.21";
8add82fc 247
248@EXPORT_OK = qw(
249 autoflush
250 output_field_separator
251 output_record_separator
252 input_record_separator
253 input_line_number
254 format_page_number
255 format_lines_per_page
256 format_lines_left
257 format_name
258 format_top_name
259 format_line_break_characters
260 format_formfeed
261 format_write
262
263 print
264 printf
265 getline
266 getlines
267
cf7fe8a2 268 printflush
269 flush
270
8add82fc 271 SEEK_SET
272 SEEK_CUR
273 SEEK_END
274 _IOFBF
275 _IOLBF
276 _IONBF
8add82fc 277);
278
8add82fc 279################################################
280## Constructors, destructors.
281##
282
283sub new {
27d4819a 284 my $class = ref($_[0]) || $_[0] || "IO::Handle";
285 @_ == 1 or croak "usage: new $class";
cf7fe8a2 286 my $io = gensym;
287 bless $io, $class;
8add82fc 288}
289
290sub new_from_fd {
27d4819a 291 my $class = ref($_[0]) || $_[0] || "IO::Handle";
292 @_ == 3 or croak "usage: new_from_fd $class FD, MODE";
cf7fe8a2 293 my $io = gensym;
c927212d 294 shift;
cf7fe8a2 295 IO::Handle::fdopen($io, @_)
8add82fc 296 or return undef;
cf7fe8a2 297 bless $io, $class;
8add82fc 298}
299
98d4926f 300#
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.
305#
306sub DESTROY {}
7a4c00b4 307
8add82fc 308
309################################################
310## Open and close.
311##
312
313sub _open_mode_string {
314 my ($mode) = @_;
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";
320 $mode;
321}
322
323sub fdopen {
cf7fe8a2 324 @_ == 3 or croak 'usage: $io->fdopen(FD, MODE)';
325 my ($io, $fd, $mode) = @_;
8add82fc 326 local(*GLOB);
327
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);
331 *GLOB = *{*$fd};
332 $fd = $n;
333 } elsif ($fd =~ m#^\d+$#) {
334 # It's an FD number; prefix with "=".
335 $fd = "=$fd";
336 }
337
cf7fe8a2 338 open($io, _open_mode_string($mode) . '&' . $fd)
339 ? $io : undef;
8add82fc 340}
341
342sub close {
cf7fe8a2 343 @_ == 1 or croak 'usage: $io->close()';
344 my($io) = @_;
8add82fc 345
cf7fe8a2 346 close($io);
8add82fc 347}
348
349################################################
350## Normal I/O functions.
351##
352
8add82fc 353# flock
8add82fc 354# select
8add82fc 355
356sub opened {
cf7fe8a2 357 @_ == 1 or croak 'usage: $io->opened()';
8add82fc 358 defined fileno($_[0]);
359}
360
361sub fileno {
cf7fe8a2 362 @_ == 1 or croak 'usage: $io->fileno()';
8add82fc 363 fileno($_[0]);
364}
365
366sub getc {
cf7fe8a2 367 @_ == 1 or croak 'usage: $io->getc()';
8add82fc 368 getc($_[0]);
369}
370
8add82fc 371sub eof {
cf7fe8a2 372 @_ == 1 or croak 'usage: $io->eof()';
8add82fc 373 eof($_[0]);
374}
375
376sub print {
cf7fe8a2 377 @_ or croak 'usage: $io->print(ARGS)';
8add82fc 378 my $this = shift;
379 print $this @_;
380}
381
382sub printf {
cf7fe8a2 383 @_ >= 2 or croak 'usage: $io->printf(FMT,[ARGS])';
8add82fc 384 my $this = shift;
385 printf $this @_;
386}
387
388sub getline {
cf7fe8a2 389 @_ == 1 or croak 'usage: $io->getline()';
8add82fc 390 my $this = shift;
391 return scalar <$this>;
392}
393
f86702cc 394*gets = \&getline; # deprecated
395
8add82fc 396sub getlines {
cf7fe8a2 397 @_ == 1 or croak 'usage: $io->getlines()';
8add82fc 398 wantarray or
cf7fe8a2 399 croak 'Can\'t call $io->getlines in a scalar context, use $io->getline';
27d4819a 400 my $this = shift;
8add82fc 401 return <$this>;
402}
403
404sub truncate {
cf7fe8a2 405 @_ == 2 or croak 'usage: $io->truncate(LEN)';
8add82fc 406 truncate($_[0], $_[1]);
407}
408
409sub read {
cf7fe8a2 410 @_ == 3 || @_ == 4 or croak 'usage: $io->read(BUF, LEN [, OFFSET])';
8add82fc 411 read($_[0], $_[1], $_[2], $_[3] || 0);
412}
413
27d4819a 414sub sysread {
cf7fe8a2 415 @_ == 3 || @_ == 4 or croak 'usage: $io->sysread(BUF, LEN [, OFFSET])';
27d4819a 416 sysread($_[0], $_[1], $_[2], $_[3] || 0);
417}
418
8add82fc 419sub write {
8fd73a68 420 @_ >= 2 && @_ <= 4 or croak 'usage: $io->write(BUF [, LEN [, OFFSET]])';
8add82fc 421 local($\) = "";
8fd73a68 422 $_[2] = length($_[1]) unless defined $_[2];
8add82fc 423 print { $_[0] } substr($_[1], $_[3] || 0, $_[2]);
424}
425
27d4819a 426sub syswrite {
8fd73a68 427 @_ >= 2 && @_ <= 4 or croak 'usage: $io->syswrite(BUF [, LEN [, OFFSET]])';
22d4bb9c 428 if (defined($_[2])) {
429 syswrite($_[0], $_[1], $_[2], $_[3] || 0);
430 } else {
431 syswrite($_[0], $_[1]);
432 }
27d4819a 433}
434
8add82fc 435sub stat {
cf7fe8a2 436 @_ == 1 or croak 'usage: $io->stat()';
8add82fc 437 stat($_[0]);
438}
439
440################################################
441## State modification functions.
442##
443
444sub autoflush {
cf7fe8a2 445 my $old = new SelectSaver qualify($_[0], caller);
8add82fc 446 my $prev = $|;
447 $| = @_ > 1 ? $_[1] : 1;
448 $prev;
449}
450
451sub output_field_separator {
cf7fe8a2 452 carp "output_field_separator is not supported on a per-handle basis"
453 if ref($_[0]);
8add82fc 454 my $prev = $,;
455 $, = $_[1] if @_ > 1;
456 $prev;
457}
458
459sub output_record_separator {
cf7fe8a2 460 carp "output_record_separator is not supported on a per-handle basis"
461 if ref($_[0]);
8add82fc 462 my $prev = $\;
463 $\ = $_[1] if @_ > 1;
464 $prev;
465}
466
467sub input_record_separator {
cf7fe8a2 468 carp "input_record_separator is not supported on a per-handle basis"
469 if ref($_[0]);
8add82fc 470 my $prev = $/;
471 $/ = $_[1] if @_ > 1;
472 $prev;
473}
474
475sub input_line_number {
91cce263 476 local $.;
477 my $tell = tell qualify($_[0], caller) if ref($_[0]);
478 my $prev = $.;
479 $. = $_[1] if @_ > 1;
480 $prev;
481}
91cce263 482
8add82fc 483sub format_page_number {
b61d194c 484 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
8add82fc 485 my $prev = $%;
486 $% = $_[1] if @_ > 1;
487 $prev;
488}
489
490sub format_lines_per_page {
b61d194c 491 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
8add82fc 492 my $prev = $=;
493 $= = $_[1] if @_ > 1;
494 $prev;
495}
496
497sub format_lines_left {
b61d194c 498 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
8add82fc 499 my $prev = $-;
500 $- = $_[1] if @_ > 1;
501 $prev;
502}
503
504sub format_name {
b61d194c 505 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
8add82fc 506 my $prev = $~;
507 $~ = qualify($_[1], caller) if @_ > 1;
508 $prev;
509}
510
511sub format_top_name {
b61d194c 512 my $old = new SelectSaver qualify($_[0], caller) if ref($_[0]);
8add82fc 513 my $prev = $^;
514 $^ = qualify($_[1], caller) if @_ > 1;
515 $prev;
516}
517
518sub format_line_break_characters {
cf7fe8a2 519 carp "format_line_break_characters is not supported on a per-handle basis"
520 if ref($_[0]);
8add82fc 521 my $prev = $:;
522 $: = $_[1] if @_ > 1;
523 $prev;
524}
525
526sub format_formfeed {
cf7fe8a2 527 carp "format_formfeed is not supported on a per-handle basis"
528 if ref($_[0]);
8add82fc 529 my $prev = $^L;
530 $^L = $_[1] if @_ > 1;
531 $prev;
532}
533
534sub formline {
cf7fe8a2 535 my $io = shift;
8add82fc 536 my $picture = shift;
537 local($^A) = $^A;
538 local($\) = "";
539 formline($picture, @_);
cf7fe8a2 540 print $io $^A;
8add82fc 541}
542
543sub format_write {
cf7fe8a2 544 @_ < 3 || croak 'usage: $io->write( [FORMAT_NAME] )';
8add82fc 545 if (@_ == 2) {
cf7fe8a2 546 my ($io, $fmt) = @_;
547 my $oldfmt = $io->format_name($fmt);
548 CORE::write($io);
549 $io->format_name($oldfmt);
8add82fc 550 } else {
56f7f34b 551 CORE::write($_[0]);
8add82fc 552 }
553}
554
21e970cc 555# XXX undocumented
27d4819a 556sub fcntl {
cf7fe8a2 557 @_ == 3 || croak 'usage: $io->fcntl( OP, VALUE );';
21e970cc 558 my ($io, $op) = @_;
559 return fcntl($io, $op, $_[2]);
27d4819a 560}
561
21e970cc 562# XXX undocumented
27d4819a 563sub ioctl {
cf7fe8a2 564 @_ == 3 || croak 'usage: $io->ioctl( OP, VALUE );';
21e970cc 565 my ($io, $op) = @_;
566 return ioctl($io, $op, $_[2]);
27d4819a 567}
8add82fc 568
cf7fe8a2 569# this sub is for compatability with older releases of IO that used
570# a sub called constant to detemine if a constant existed -- GMB
571#
572# The SEEK_* and _IO?BF constants were the only constants at that time
573# any new code should just chech defined(&CONSTANT_NAME)
574
575sub constant {
576 no strict 'refs';
577 my $name = shift;
578 (($name =~ /^(SEEK_(SET|CUR|END)|_IO[FLN]BF)$/) && defined &{$name})
579 ? &{$name}() : undef;
580}
581
582
583# so that flush.pl can be depriciated
584
585sub printflush {
586 my $io = shift;
587 my $old = new SelectSaver qualify($io, caller) if ref($io);
588 local $| = 1;
589 if(ref($io)) {
590 print $io @_;
591 }
592 else {
593 print @_;
594 }
595}
596
8add82fc 5971;