IO::Scalar - IO:: interface for reading/writing a scalar |
IO::Scalar - IO:: interface for reading/writing a scalar
If you have any Perl5, you can use the basic OO interface...
use IO::Scalar;
# Open a handle on a string: $SH = new IO::Scalar; $SH->open(\$somestring);
# Open a handle on a string, read it line-by-line, then close it: $SH = new IO::Scalar \$somestring; while ($_ = $SH->getline) { print "Line: $_" } $SH->close;
# Open a handle on a string, and slurp in all the lines: $SH = new IO::Scalar \$somestring; print $SH->getlines;
# Open a handle on a string, and append to it: $SH = new IO::Scalar \$somestring $SH->print("bar\n"); ### will add "bar\n" to the end
# Get the current position: $pos = $SH->getpos; ### $SH->tell() also works
# Set the current position: $SH->setpos($pos); ### $SH->seek(POS,WHENCE) also works
# Open an anonymous temporary scalar: $SH = new IO::Scalar; $SH->print("Hi there!"); print "I got: ", ${$SH->sref}, "\n"; ### get at value
If your Perl is 5.004 or later, you can use the TIEHANDLE interface, and read/write scalars just like files:
use IO::Scalar;
# Writing to a scalar... my $s; tie *OUT, 'IO::Scalar', \$s; print OUT "line 1\nline 2\n", "line 3\n"; print "s is now... $s\n"
# Reading and writing an anonymous scalar... tie *OUT, 'IO::Scalar'; print OUT "line 1\nline 2\n", "line 3\n"; tied(OUT)->seek(0,0); while (<OUT>) { print "LINE: ", $_ }
This class implements objects which behave just like FileHandle (or IO::Handle) objects, except that you may use them to write to (or read from) scalars. They can be tiehandle'd as well.
Basically, this:
my $s; $SH = new IO::Scalar \$s; $SH->print("Hel", "lo, "); # OO style $SH->print("world!\n"); # ditto
Or this (if you have 5.004 or later):
my $s; $SH = tie *OUT, 'IO::Scalar', \$s; print OUT "Hel", "lo, "; # non-OO style print OUT "world!\n"; # ditto
Or this (if you have 5.004 or later):
my $s; $SH = IO::Scalar->new_tie(\$s); $SH->print("Hel", "lo, "); # OO style... print $SH "world!\n"; # ...or non-OO style!
Causes $s to be set to:
"Hello, world!\n"
Returns the self object on success, undefined on error.
croak()
if accidentally called in a scalar context.
Warning: Currently, this always causes a ``seek to the end of the string''; this may change in the future.
getpos()
.
$Id: Scalar.pm,v 1.114 1998/12/16 02:00:04 eryq Exp $
Eryq (eryq@zeegee.com). President, ZeeGee Software Inc (http://www.zeegee.com).
Thanks to Andy Glew for contributing getc()
.
Thanks to Brandon Browning for suggesting opened()
.
Thanks to David Richter for finding and fixing the bug in PRINTF()
.
IO::Scalar - IO:: interface for reading/writing a scalar |