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: ", $_ }
Stringification now works, too!
my $SH = new IO::Scalar \$somestring;
$SH->print("Hello, ");
$SH->print("world!");
print "I've got: <$SH>\n";
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.
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.121 2000/09/05 03:53:58 eryq Exp $
Eryq (
Thanks to the following individuals for their invaluable contributions (if I've forgotten or misspelled your name, please email me!):
Andy Glew,
for contributing getc()
.
Brandon Browning,
for suggesting opened()
.
David Richter,
for finding and fixing the bug in PRINTF()
.
Eric L. Brine, for his offset-using read() and write() implementations.
Rich (at Annexia),
for his patch to massively improve the performance of getline()
.