Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

FAQ 5.12 How can I open a filehandle to a string?

0 views
Skip to first unread message

PerlFAQ Server

unread,
May 26, 2008, 3:03:02 PM5/26/08
to
This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

5.12: How can I open a filehandle to a string?

, , ,
(contributed by Peter J. Holzer, hjp-u...@hjp.at)

Since Perl 5.8.0, you can pass a reference to a scalar instead of the
filename to create a file handle which you can used to read from or
write to a string:

open(my $fh, '>', \$string) or die "Could not open string for writing";
print $fh "foo\n";
print $fh "bar\n"; # $string now contains "foo\nbar\n"

open(my $fh, '<', \$string) or die "Could not open string for reading";
my $x = <$fh>; # $x now contains "foo\n"

With older versions of Perl, the "IO::String" module provides similar
functionality.

--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.

Bill H

unread,
May 26, 2008, 3:19:21 PM5/26/08
to
[snip]

> 5.12: How can I open a filehandle to a string?
>
> , , ,
>     (contributed by Peter J. Holzer, hjp-usen...@hjp.at)

>
>     Since Perl 5.8.0, you can pass a reference to a scalar instead of the
>     filename to create a file handle which you can used to read from or
>     write to a string:
>
>             open(my $fh, '>', \$string) or die "Could not open string for writing";
>             print $fh "foo\n";
>             print $fh "bar\n";      # $string now contains "foo\nbar\n"
>
>             open(my $fh, '<', \$string) or die "Could not open string for reading";
>             my $x = <$fh>;  # $x now contains "foo\n"
>
>     With older versions of Perl, the "IO::String" module provides similar
>     functionality.
>
[snip]

This is interesting, but what real world examples would there be to
doing this instead of just using string functions? The only one I can
think of is to redirect file output to a string for debugging
purposes, or maybe for duplication purposes, direct to a string, write
to a file, write to another etc.

Bill H

Uri Guttman

unread,
May 26, 2008, 3:40:13 PM5/26/08
to
>>>>> "BH" == Bill H <bi...@ts1000.us> writes:

BH> [snip]


>> 5.12: How can I open a filehandle to a string?
>>
>> , , ,
>>     (contributed by Peter J. Holzer, hjp-usen...@hjp.at)
>>
>>     Since Perl 5.8.0, you can pass a reference to a scalar instead of the
>>     filename to create a file handle which you can used to read from or
>>     write to a string:
>>
>>             open(my $fh, '>', \$string) or die "Could not open string for writing";
>>             print $fh "foo\n";
>>             print $fh "bar\n";      # $string now contains "foo\nbar\n"
>>
>>             open(my $fh, '<', \$string) or die "Could not open string for reading";
>>             my $x = <$fh>;  # $x now contains "foo\n"
>>
>>     With older versions of Perl, the "IO::String" module provides similar
>>     functionality.
>>

BH> [snip]

BH> This is interesting, but what real world examples would there be to
BH> doing this instead of just using string functions? The only one I can
BH> think of is to redirect file output to a string for debugging
BH> purposes, or maybe for duplication purposes, direct to a string, write
BH> to a file, write to another etc.

there are many uses. sometimes you have data and some parsing modules
expect a file handle. or some module expects to print to a file and you
want to put the data elsewhere (or use it in two places). even the list
you provided are all real world uses. sure you don't do this everyday
but it will come up once in a while and it is good that it is easy to
use. the previous way was with a tied handle module which is much
slower.

uri

--
Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
--------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------

brian d foy

unread,
May 26, 2008, 4:46:49 PM5/26/08
to
In article
<6669364b-16cb-4252...@26g2000hsk.googlegroups.com>,
Bill H <bi...@ts1000.us> wrote:

> [snip]
> > 5.12: How can I open a filehandle to a string?

> This is interesting, but what real world examples would there be to


> doing this instead of just using string functions?

I usually need this where some module insists on having a filehandle to
send its data to, but I want it in a string without all the extra work
and left-over files. Now I can print to a string directly.

Peter J. Holzer

unread,
May 29, 2008, 5:57:50 PM5/29/08
to
On 2008-05-26 19:03, PerlFAQ Server <br...@stonehenge.com> wrote:
> --------------------------------------------------------------------
>
> 5.12: How can I open a filehandle to a string?
>
> , , ,

I think the commas in

| X<string>, X<open>, X<IO::Scalar>, X<filehandle>

should be omitted.

> (contributed by Peter J. Holzer, hjp-u...@hjp.at)
>
> Since Perl 5.8.0, you can pass a reference to a scalar instead of the
> filename to create a file handle which you can used to read from or
> write to a string:

Yikes! Did I really create that monster of a sentence (not to mention
the typo)? I guess it shows that German is my native language. How about
this?

| Since Perl 5.8.0 a file handle referring to a string can be created by
| calling open with a reference to that string instead of the filename.
| This file handle can then be used to read from or write to the string:

hp

Peter J. Holzer

unread,
May 29, 2008, 6:15:13 PM5/29/08
to

I find this especially handy in test scripts. For example, here's an
excerpt from a test script for a project I'm currently working on:

my $s;
close(STDOUT);

my $id = $dataset->id;

open(STDOUT, '>', \$s);
$dataset->print('xml');
ok(index($s, "<d:id>$id</d:id>") != -1, "generated XML contains <d:id>$id</d:id>");
ok(index($s, "<d:description xml:lang='de'") != -1, "generated XML contains german description");

(in this case $dataset also has a method as_xml, which returns the XML
representation as a string. So this test mainly serves to ensure that
print really calls as_xml and prints the result to STDOUT. But it might
actually be useful to turn them around: Put all the logic into print and
then implement as_xml as a wrapper around print - this safes memory when
you are only printing and allows pipeling the produces and the consumer
of the XML file)

hp

Bill H

unread,
May 29, 2008, 6:42:19 PM5/29/08
to
On May 29, 6:15 pm, "Peter J. Holzer" <hjp-usen...@hjp.at> wrote:
> On 2008-05-26 20:46, brian d foy <brian.d....@gmail.com> wrote:
>
> > In article
> ><6669364b-16cb-4252-b0c7-8ab49bf24...@26g2000hsk.googlegroups.com>,

I like this idea Peter. I am starting to do a lot of xml processing
via perl and this may come in handy.

Thanks, Bill H

Ben Morrow

unread,
May 29, 2008, 10:02:29 PM5/29/08
to

Quoth "Peter J. Holzer" <hjp-u...@hjp.at>:

>
> Yikes! Did I really create that monster of a sentence (not to mention
> the typo)? I guess it shows that German is my native language. How about
> this?
>
> | Since Perl 5.8.0 a file handle referring to a string can be created by
> | calling open with a reference to that string instead of the filename.
> | This file handle can then be used to read from or write to the string:

| Since Perl 5.8.0 a file handle can be used to read and write the
| contents of a scalar instead of a file on disk. This is done by
| passing C<open> a reference in place of a filename:

The important part is 'this handle doesn't actually point to a file'.
The detail of passing a reference should come later.

Ben

--
Razors pain you / Rivers are damp
Acids stain you / And drugs cause cramp. [Dorothy Parker]
Guns aren't lawful / Nooses give
Gas smells awful / You might as well live. b...@morrow.me.uk

Peter J. Holzer

unread,
May 30, 2008, 9:47:45 AM5/30/08
to
On 2008-05-30 02:02, Ben Morrow <b...@morrow.me.uk> wrote:
> Quoth "Peter J. Holzer" <hjp-u...@hjp.at>:
>> Yikes! Did I really create that monster of a sentence (not to mention
>> the typo)? I guess it shows that German is my native language. How about
>> this?
>>
>> | Since Perl 5.8.0 a file handle referring to a string can be created by
>> | calling open with a reference to that string instead of the filename.
>> | This file handle can then be used to read from or write to the string:
>
>| Since Perl 5.8.0 a file handle can be used to read and write the
>| contents of a scalar instead of a file on disk. This is done by
>| passing C<open> a reference in place of a filename:
>
> The important part is 'this handle doesn't actually point to a file'.
> The detail of passing a reference should come later.

Yes, that's better.

hp

David Combs

unread,
Jun 24, 2008, 10:52:47 AM6/24/08
to

The suggested examples and uses all concern writing *to* a string.

How about for reading *from* a string?

What are some of the (possible) uses for doing that?


And -- what about "peek" on such a thing?

And a "putback", as for when you have to look-ahead?


-----


Re reading *and writing* to/from a string (pretending to be
an open file), what are some of the useful perl-operations
already existing for *files*, for which there's no corresponding
perl-op for *strings*, which you can get at via the kludge
of pretending it's a file?


I think such a discussion here (in the faq) could lead to
lots of interesting (and useful!) programming-tricks!

David


brian d foy

unread,
Jun 24, 2008, 12:25:15 PM6/24/08
to
In article <g3r1nv$c6s$1...@reader2.panix.com>, David Combs
<dkc...@panix.com> wrote:

> The suggested examples and uses all concern writing *to* a string.
>
> How about for reading *from* a string?

Yeah, I was just thinking about that since I had added some of that
stuff to our Intermediate Perl class. Now I just have to add it to the
FAQ :)

brian d foy

unread,
Jun 24, 2008, 1:03:14 PM6/24/08
to
On May 29, 4:57 pm, "Peter J. Holzer" <hjp-usen...@hjp.at> wrote:

> > 5.12: How can I open a filehandle to a string?

> >     Since Perl 5.8.0, you can pass a reference to a scalar instead of the


> >     filename to create a file handle which you can used to read from or
> >     write to a string:
>
> Yikes! Did I really create that monster of a sentence (not to mention
> the typo)? I guess it shows that German is my native language. How about
> this?
>
> | Since Perl 5.8.0 a file handle referring to a string can be created by
> | calling open with a reference to that string instead of the filename.
> | This file handle can then be used to read from or write to the string:


I've updated the answer with your new paragraph, which now has 200% of
the
sentences of the former entry. :)

Peter J. Holzer

unread,
Jun 25, 2008, 7:57:29 PM6/25/08
to
On 2008-06-24 14:52, David Combs <dkc...@panix.com> wrote:
> The suggested examples and uses all concern writing *to* a string.

Nope.

> How about for reading *from* a string?

See the second example:

| open(my $fh, '<', \$string) or die "Could not open string for readin


| my $x = <$fh>; # $x now contains "foo\n"

> What are some of the (possible) uses for doing that?

Basically the same: You have a method or function which expects a file
handle, but the data is in a string.

hp

0 new messages