Cooking with Perl
by Tom Christiansen, Nathan Torkington
|
Pages: 1, 2
Sample Recipe: Pretending a String Is a File
Problem
You have data in string, but would like to treat it as a file. For example, you have a subroutine that expects a filehandle as an argument, but you would like that subroutine to work directly on the data in your string instead. Additionally, you don't want to write the data to a temporary file.
Solution
Use the scalar I/O in Perl v5.8:
open($fh, "+<", \$string); # read and write contents of $string
Discussion
Perl's I/O layers include support for input and output from a
scalar. When you read a record with <$fh>, you
are reading the next line from $string. When you
write a record with print, you change $string. You can pass $fh to a
function that expects a filehandle, and that subroutine need never know that
it's really working with data in a string.
Perl respects the various access modes in open for strings, so you can specify that the strings be
opened as read-only, with truncation, in append mode, and so on:
open($fh, "<", \$string); # read only
open($fh, ">", \$string); # write only, discard original contents
open($fh, "+>", \$string); # read and write, discard original contents
open($fh, "+<", \$string); # read and write, preserve original contents
These handles behave in all respects like regular filehandles, so
all I/O functions work, such as seek, truncate, sysread, and
friends.
See Also
The open function in perlfunc(1) and in Chapter 29 ("Functions") of Programming Perl, 3rd Edition; "Using Random-Access I/O;" and "Setting
the Default I/O Layers"
O'Reilly & Associates will soon release (August 2003) Perl Cookbook, 2nd Edition.
- Sample Chapter 1, Strings is available free online.
- You can also look at the Table of Contents, the Index, and the full description of the book.
- For more information, or to order the book, click here.

