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