6 IO::Scalar - IO:: interface for reading/writing a scalar
11 Perform I/O on strings, using the basic OO interface...
15 $data = "My message:\n";
17 ### Open a handle on a string, and append to it:
18 $SH = new IO::Scalar \$data;
20 $SH->print(", world!\nBye now!\n");
21 print "The string is now: ", $data, "\n";
23 ### Open a handle on a string, read it line-by-line, then close it:
24 $SH = new IO::Scalar \$data;
25 while (defined($_ = $SH->getline)) {
30 ### Open a handle on a string, and slurp in all the lines:
31 $SH = new IO::Scalar \$data;
32 print "All lines:\n", $SH->getlines;
34 ### Get the current position (either of two ways):
38 ### Set the current position (either of two ways):
40 $SH->seek($offset, 0);
42 ### Open an anonymous temporary scalar:
44 $SH->print("Hi there!");
45 print "I printed: ", ${$SH->sref}, "\n"; ### get at value
48 Don't like OO for your I/O? No problem.
49 Thanks to the magic of an invisible tie(), the following now
50 works out of the box, just as it does with IO::Handle:
54 $data = "My message:\n";
56 ### Open a handle on a string, and append to it:
57 $SH = new IO::Scalar \$data;
59 print $SH ", world!\nBye now!\n";
60 print "The string is now: ", $data, "\n";
62 ### Open a handle on a string, read it line-by-line, then close it:
63 $SH = new IO::Scalar \$data;
69 ### Open a handle on a string, and slurp in all the lines:
70 $SH = new IO::Scalar \$data;
71 print "All lines:\n", <$SH>;
73 ### Get the current position (WARNING: requires 5.6):
76 ### Set the current position (WARNING: requires 5.6):
79 ### Open an anonymous temporary scalar:
81 print $SH "Hi there!";
82 print "I printed: ", ${$SH->sref}, "\n"; ### get at value
85 And for you folks with 1.x code out there: the old tie() style still works,
86 though this is I<unnecessary and deprecated>:
90 ### Writing to a scalar...
92 tie *OUT, 'IO::Scalar', \$s;
93 print OUT "line 1\nline 2\n", "line 3\n";
94 print "String is now: $s\n"
96 ### Reading and writing an anonymous scalar...
97 tie *OUT, 'IO::Scalar';
98 print OUT "line 1\nline 2\n", "line 3\n";
101 print "Got line: ", $_;
105 Stringification works, too!
107 my $SH = new IO::Scalar \$data;
110 print "I printed: $SH\n";
116 This class is part of the IO::Stringy distribution;
117 see L<IO::Stringy> for change log and general information.
119 The IO::Scalar class implements objects which behave just like
120 IO::Handle (or FileHandle) objects, except that you may use them
121 to write to (or read from) scalars. These handles are
122 automatically tiehandle'd (though please see L<"WARNINGS">
123 for information relevant to your Perl version).
129 $SH = new IO::Scalar \$s;
130 $SH->print("Hel", "lo, "); ### OO style
131 $SH->print("world!\n"); ### ditto
136 $SH = tie *OUT, 'IO::Scalar', \$s;
137 print OUT "Hel", "lo, "; ### non-OO style
138 print OUT "world!\n"; ### ditto
140 Causes $s to be set to:
145 =head1 PUBLIC INTERFACE
151 use vars qw($VERSION @ISA);
156 ### Stringification, courtesy of B. K. Oxley (binkley): :-)
157 use overload '""' => sub { ${*{$_[0]}->{SR}} };
158 use overload 'bool' => sub { 1 }; ### have to do this, so object is true!
160 ### The package version, both in 1.23 style *and* usable by MakeMaker:
164 @ISA = qw(IO::Handle);
166 ### This stuff should be got rid of ASAP.
167 require IO::WrapTie and push @ISA, 'IO::WrapTie::Slave' if ($] >= 5.004);
169 #==============================
177 #------------------------------
182 Return a new, unattached scalar handle.
183 If any arguments are given, they're sent to open().
189 my $class = ref($proto) || $proto;
190 my $self = bless \do { local *FH }, $class;
191 tie *$self, $class, $self;
192 $self->open(@_); ### open on anonymous by default
199 #------------------------------
201 =item open [SCALARREF]
204 Open the scalar handle on a new scalar, pointed to by SCALARREF.
205 If no SCALARREF is given, a "private" scalar is created to hold
208 Returns the self object on success, undefined on error.
213 my ($self, $sref) = @_;
216 defined($sref) or do {my $s = ''; $sref = \$s};
217 (ref($sref) eq "SCALAR") or croak "open() needs a ref to a scalar";
220 *$self->{Pos} = 0; ### seek position
221 *$self->{SR} = $sref; ### scalar reference
225 #------------------------------
230 Is the scalar handle opened on something?
238 #------------------------------
243 Disassociate the scalar handle from its underlying scalar.
244 Done automatically on destroy.
260 #==============================
262 =head2 Input and output
269 #------------------------------
274 No-op, provided for OO compatibility.
278 sub flush { "0 but true" }
280 #------------------------------
285 Return the next character, or undef if none remain.
292 ### Return undef right away if at EOF; else, move pos forward:
293 return undef if $self->eof;
294 substr(${*$self->{SR}}, *$self->{Pos}++, 1);
297 #------------------------------
302 Return the next line, or undef on end of string.
303 Can safely be called in an array context.
304 Currently, lines are delimited by "\n".
311 ### Return undef right away if at EOF:
312 return undef if $self->eof;
315 my $sr = *$self->{SR};
316 my $i = *$self->{Pos}; ### Start matching at this point.
318 ### Minimal impact implementation!
319 ### We do the fast fast thing (no regexps) if using the
320 ### classic input record separator.
322 ### Case 1: $/ is undef: slurp all...
324 *$self->{Pos} = length $$sr;
325 return substr($$sr, $i);
328 ### Case 2: $/ is "\n": zoom zoom zoom...
329 elsif ($/ eq "\012") {
331 ### Seek ahead for "\n"... yes, this really is faster than regexps.
332 my $len = length($$sr);
333 for (; $i < $len; ++$i) {
334 last if ord (substr ($$sr, $i, 1)) == 10;
337 ### Extract the line:
339 if ($i < $len) { ### We found a "\n":
340 $line = substr ($$sr, *$self->{Pos}, $i - *$self->{Pos} + 1);
341 *$self->{Pos} = $i+1; ### Remember where we finished up.
343 else { ### No "\n"; slurp the remainder:
344 $line = substr ($$sr, *$self->{Pos}, $i - *$self->{Pos});
345 *$self->{Pos} = $len;
350 ### Case 3: $/ is ref to int. Do fixed-size records.
351 ### (Thanks to Dominique Quatravaux.)
353 my $len = length($$sr);
355 my $line = substr ($$sr, *$self->{Pos}, $i);
357 *$self->{Pos} = $len if (*$self->{Pos} > $len);
361 ### Case 4: $/ is either "" (paragraphs) or something weird...
362 ### This is Graham's general-purpose stuff, which might be
363 ### a tad slower than Case 2 for typical data, because
368 ### If in paragraph mode, skip leading lines (and update i!):
370 (($$sr =~ m/\G\n*/g) and ($i = pos($$sr)));
372 ### If we see the separator in the buffer ahead...
374 ? $$sr =~ m,\Q$/\E,g ### (ordinary sep) TBD: precomp!
375 : $$sr =~ m,\n\n,g ### (a paragraph)
377 *$self->{Pos} = pos $$sr;
378 return substr($$sr, $i, *$self->{Pos}-$i);
380 ### Else if no separator remains, just slurp the rest:
382 *$self->{Pos} = length $$sr;
383 return substr($$sr, $i);
388 #------------------------------
393 Get all remaining lines.
394 It will croak() if accidentally called in a scalar context.
400 wantarray or croak("can't call getlines in scalar context!");
402 push @lines, $line while (defined($line = $self->getline));
406 #------------------------------
411 Print ARGS to the underlying scalar.
413 B<Warning:> this continues to always cause a seek to the end
414 of the string, but if you perform seek()s and tell()s, it is
415 still safer to explicitly seek-to-end before subsequent print()s.
421 *$self->{Pos} = length(${*$self->{SR}} .= join('', @_) . (defined($\) ? $\ : ""));
426 my $append = join('', @_) . $\;
427 ${*$self->{SR}} .= $append;
428 *$self->{Pos} += length($append);
433 ${*$self->{SR}} .= join('', @_) . $\;
434 *$self->{Pos} = length(${*$self->{SR}});
439 #------------------------------
441 =item read BUF, NBYTES, [OFFSET]
444 Read some bytes from the scalar.
445 Returns the number of bytes actually read, 0 on end-of-file, undef on error.
452 my $off = $_[3] || 0;
454 my $read = substr(${*$self->{SR}}, *$self->{Pos}, $n);
457 ($off ? substr($_[1], $off) : $_[1]) = $read;
461 #------------------------------
463 =item write BUF, NBYTES, [OFFSET]
466 Write some bytes to the scalar.
473 my $off = $_[3] || 0;
475 my $data = substr($_[1], $off, $n);
481 #------------------------------
483 =item sysread BUF, LEN, [OFFSET]
486 Read some bytes from the scalar.
487 Returns the number of bytes actually read, 0 on end-of-file, undef on error.
496 #------------------------------
498 =item syswrite BUF, NBYTES, [OFFSET]
501 Write some bytes to the scalar.
515 #==============================
517 =head2 Seeking/telling and other attributes
524 #------------------------------
529 No-op, provided for OO compatibility.
535 #------------------------------
540 No-op, provided for OO compatibility.
546 #------------------------------
550 I<Instance method.> Clear the error and EOF flags. A no-op.
556 #------------------------------
560 I<Instance method.> Are we at end of file?
566 (*$self->{Pos} >= length(${*$self->{SR}}));
569 #------------------------------
571 =item seek OFFSET, WHENCE
573 I<Instance method.> Seek to a given position in the stream.
578 my ($self, $pos, $whence) = @_;
579 my $eofpos = length(${*$self->{SR}});
582 if ($whence == 0) { *$self->{Pos} = $pos } ### SEEK_SET
583 elsif ($whence == 1) { *$self->{Pos} += $pos } ### SEEK_CUR
584 elsif ($whence == 2) { *$self->{Pos} = $eofpos + $pos} ### SEEK_END
585 else { croak "bad seek whence ($whence)" }
588 if (*$self->{Pos} < 0) { *$self->{Pos} = 0 }
589 if (*$self->{Pos} > $eofpos) { *$self->{Pos} = $eofpos }
593 #------------------------------
595 =item sysseek OFFSET, WHENCE
597 I<Instance method.> Identical to C<seek OFFSET, WHENCE>, I<q.v.>
606 #------------------------------
611 Return the current position in the stream, as a numeric offset.
615 sub tell { *{shift()}->{Pos} }
617 #------------------------------
621 # I<Instance method.>
622 # Obey the curent setting of $/, like IO::Handle does?
623 # Default is false in 1.x, but cold-welded true in 2.x and later.
626 my ($self, $yesno) = @_;
627 carp "use_RS is deprecated and ignored; \$/ is always consulted\n";
630 #------------------------------
635 Set the current position, using the opaque value returned by C<getpos()>.
639 sub setpos { shift->seek($_[0],0) }
641 #------------------------------
646 Return the current position in the string, as an opaque object.
653 #------------------------------
658 Return a reference to the underlying scalar.
662 sub sref { *{shift()}->{SR} }
665 #------------------------------
666 # Tied handle methods...
667 #------------------------------
669 # Conventional tiehandle interface:
671 ((defined($_[1]) && UNIVERSAL::isa($_[1], "IO::Scalar"))
675 sub GETC { shift->getc(@_) }
676 sub PRINT { shift->print(@_) }
677 sub PRINTF { shift->print(sprintf(shift, @_)) }
678 sub READ { shift->read(@_) }
679 sub READLINE { wantarray ? shift->getlines(@_) : shift->getline(@_) }
680 sub WRITE { shift->write(@_); }
681 sub CLOSE { shift->close(@_); }
682 sub SEEK { shift->seek(@_); }
683 sub TELL { shift->tell(@_); }
684 sub EOF { shift->eof(@_); }
686 #------------------------------------------------------------
701 Perl's TIEHANDLE spec was incomplete prior to 5.005_57;
702 it was missing support for C<seek()>, C<tell()>, and C<eof()>.
703 Attempting to use these functions with an IO::Scalar will not work
704 prior to 5.005_57. IO::Scalar will not have the relevant methods
705 invoked; and even worse, this kind of bug can lie dormant for a while.
706 If you turn warnings on (via C<$^W> or C<perl -w>),
707 and you see something like this...
709 attempt to seek on unopened filehandle
711 ...then you are probably trying to use one of these functions
712 on an IO::Scalar with an old Perl. The remedy is to simply
713 use the OO version; e.g.:
715 $SH->seek(0,0); ### GOOD: will work on any 5.005
716 seek($SH,0,0); ### WARNING: will only work on 5.005_57 and beyond
721 $Id: Scalar.pm,v 1.6 2005/02/10 21:21:53 dfs Exp $
726 =head2 Primary Maintainer
728 David F. Skoll (F<dfs@roaringpenguin.com>).
730 =head2 Principal author
732 Eryq (F<eryq@zeegee.com>).
733 President, ZeeGee Software Inc (F<http://www.zeegee.com>).
736 =head2 Other contributors
738 The full set of contributors always includes the folks mentioned
739 in L<IO::Stringy/"CHANGE LOG">. But just the same, special
740 thanks to the following individuals for their invaluable contributions
741 (if I've forgotten or misspelled your name, please email me!):
744 for contributing C<getc()>.
747 for suggesting C<opened()>.
750 for finding and fixing the bug in C<PRINTF()>.
753 for his offset-using read() and write() implementations.
756 for his patches to massively improve the performance of C<getline()>
757 and add C<sysread> and C<syswrite>.
759 I<B. K. Oxley (binkley),>
760 for stringification and inheritance improvements,
761 and sundry good ideas.
764 for the IO::Handle inheritance and automatic tie-ing.
769 L<IO::String>, which is quite similar but which was designed
770 more-recently and with an IO::Handle-like interface in mind,
771 so you could mix OO- and native-filehandle usage without using tied().
773 I<Note:> as of version 2.x, these classes all work like
774 their IO::Handle counterparts, so we have comparable
775 functionality to IO::String.