Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Answer: How do I print formatted text to a scalar instead of a filehandle?

by shmem (Chancellor)
on Jan 05, 2007 at 00:54 UTC ( #593050=categorized answer: print w/replies, xml ) Need Help??

Q&A > input and output > How do I print formatted text to a scalar instead of a filehandle? - Answer contributed by shmem

Since Perl 5.8.0 you can open a filehandle for writing to a scalar. Then, if you make that filehandle the default, writes will go there.

my %hash = (one => 1, two => 2, three => 3); my $output; open FH, '>', \$output; my $old_fh = select(FH); my $key; foreach $key (keys %hash) { write; } select ($old_fh); print $output; format FH = @<<<<<<<<< @## $key, $hash{$key} .
Content of $output:
three 3 one 1 two 2

Unfortunately, this doesn't seem to work with localized filehandles.

Log In?

What's my password?
Create A New User
[atcroft]: PriNet: Those code bits worked for me, with test hashes, but I didn't test it with more than a few simple test cases. *shrug* Had hoped it would help, at least.
[PriNet]: i think i found the problem, the "source" array that sets the individual key values isn't being cleared, it's keeping the previous values...
[atcroft]: PriNet: You might consider posting a small, self-contained snippet of that segment of your code, and see if someone else has a better idea.....
[atcroft]: PriNet: Ahhh... interesting.

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2017-06-28 03:14 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (619 votes). Check out past polls.