Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

612 lines
16 KiB

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