Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

( #593048=categorized question: print w/ replies, xml ) Need Help??
Contributed by kwaping on Jan 05, 2007 at 00:18 UTC
Q&A  > input and output


Description:

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

Answer: How do I print formatted text to a scalar instead of a filehandle?
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.

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

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
Answer: How do I print formatted text to a scalar instead of a filehandle?
contributed by GrandFather

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;
Answer: How do I print formatted text to a scalar instead of a filehandle?
contributed by MidLifeXis

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 $!;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others rifling through the Monastery: (8)
    As of 2014-08-20 05:22 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The best computer themed movie is:











      Results (105 votes), past polls