astroboy has asked for the wisdom of the Perl Monks concerning the following question:

I'd like to use "format" and "write" to generate a report to a variable rather than a filehandle. Is this possible?

Replies are listed 'Best First'.
•Re: writing to a variable
by merlyn (Sage) on Oct 20, 2003 at 15:37 UTC
      Thanks all for your replies. Unfortunately we're using Perl 5.6, Win32. We can't go to 5.8, as some of the libraries don't exist for that version. Likewise, IO::Scalar isn't available as a ppm package. However, I have tried using IO::String - and I'm obviously missing something. I'm a newbie, so apologies in advance for whatever is wrong with my code:
      use IO::String; use strict; my $output; tie *IO, IO::String->new($output); my $col1 = "first"; my $col2 = "second"; write (IO); print $output; format IO = =============== ==================== @<<<<<<<<<<<<<: @<<<<<<<<<<<<<<<<<<< $col1, $col2
      I was hoping that printing $output would give me the report. Any advice appreciated
Re: writing to a variable
by jdporter (Paladin) on Oct 20, 2003 at 15:39 UTC
    Of course! Read up on the built-in function formline. Formats use this function internally, but you can call it yourself too.

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

Re: writing to a variable
by jeffa (Bishop) on Oct 20, 2003 at 15:37 UTC
Re: writing to a variable
by rinceWind (Monsignor) on Oct 20, 2003 at 16:41 UTC
    If you are writing new code, you ought to consider abandoning "format" and "write", which will be deprecated in Perl 6, in favour of TheDamian's Text::Reform. See also this thread

    --
    I'm Not Just Another Perl Hacker
Re: writing to a variable
by davido (Cardinal) on Oct 20, 2003 at 17:44 UTC
    To illustrate the "open to a scalar ref" method..... According to perldoc -fopen, "File handles can be opened to 'in memory' files held in Perl scalars..."

    open( $fh, '>', \$variable ) or ....

    I've tinkered with this construct both with the '>' and '>>' style of open. You have to be sure to close the filehandle before you access the variable directly again, or you get into race-condition problems.

    I realize that you said you can't use Perl version 5.8.0. And AFAIK this is a new 5.8.0 feature. But I mention it hopefully for the benefit of someone.


    Dave


    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein