http://www.perlmonks.org?node_id=593048

kwaping has asked for the wisdom of the Perl Monks concerning the following question: (input and output)

I want to "write" formatted text to a scalar variable instead of to a filehandle.

Originally posted as a Categorized Question.

  • Comment on How do I print formatted text to a scalar instead of a filehandle?

Replies are listed 'Best First'.
Re: How do I print formatted text to a scalar instead of a filehandle?
by shmem (Chancellor) on Jan 05, 2007 at 00:54 UTC

    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.

Re: How do I print formatted text to a scalar instead of a filehandle?
by GrandFather (Saint) on Jan 05, 2007 at 01:15 UTC

    Writing to a scalar is a pretty good way to do it:

    use strict; use warnings; my %hash = (one => 1, two => 2, three => 3); # create a format picture for use with formline format OUTPUT = @<<<<<<<<< @## $_, $hash{$_} . my $str; open OUTPUT, '>', \$str; write OUTPUT foreach sort keys %hash; close OUTPUT; print $str;
Re: How do I print formatted text to a scalar instead of a filehandle?
by kwaping (Priest) on Jan 05, 2007 at 00:19 UTC

    tie won't work, unfortunately. Here's a little trick that'll let you fudge it, with thanks to runrig's snippet for the inspiration/pointer and perldoc for the details.

    ### see perldocs perlvar, perlform, and formline for more details my $output; my %hash = (one => 1, two => 2, three => 3); # create a format picture for use with formline my $picture = '@<<<<<<<<< @##' . $/; foreach my $key (keys %hash) { # clear out the special variable $^A ("$ACCUMULATOR") $^A = ''; # again, see perldoc formline for details formline($picture,$key,$hash{$key}); # add the contents of $^A to $output $output .= $^A; } print $output;
    the output:
    one 1 two 2 three 3
Re: How do I print formatted text to a scalar instead of a filehandle?
by MidLifeXis (Monsignor) on Oct 29, 2008 at 19:50 UTC
    From output generated by Test::Inline
    package Catch; sub TIEHANDLE { my($class, $var) = @_; return bless { var => $var }, $class; } sub PRINT { my($self) = shift; ${'main::'.$self->{var}} .= join '', @_; } sub OPEN {} # XXX Hackery in case the user redirects sub CLOSE {} # XXX STDERR/STDOUT. This is not the behavior we want +. sub READ {} sub READLINE {} sub GETC {} package main; # pre-5.8.0's warns aren't caught by a tied STDERR. $SIG{__WARN__} = sub { $main::_STDERR_ .= join '', @_; }; tie *STDOUT, 'Catch', '_STDOUT_' or die $!; tie *STDERR, 'Catch', '_STDERR_' or die $!;