m-rau has asked for the wisdom of the Perl Monks concerning the following question:

I'd like to use Perl formats (document perlform). But I do not want to send the output to a file handle. Instead, I need to copy the formatted output to a variable. Question is, if there is something like a corresponding swrite function to swrite as there is a sprintf function to printf? Alternatively, do I completely miss the point???

printf and sprintf:
my $var = 'world'; printf "Hello %s.\n", $var; # goes to STDOUT my $out = sprintf "Hello %s.\n", $var; # goes to $out


write but no swrite:
my $var = 'world'; format STDOUT = Hello @>>>>>>>>>>>>>>> $var . write; # goes to STDOUT # my $out = swrite; # I NEED HELP!

Replies are listed 'Best First'.
Re: Perl formats without file handles
by gellyfish (Monsignor) on Feb 11, 2005 at 11:40 UTC

    With recent perls you can open a filehandle to a scalar:

    my $out = ''; + open OUTH, '>', \$out; + my $var = 'world'; format OUTH = Hello @>>>>>>>>>>>>>>> $var . write OUTH; + print $out;

    /J\

Re: Perl formats without file handles
by sasikumar (Monk) on Feb 11, 2005 at 11:33 UTC
    Hi

    Is this what you expect for??
    use Carp; sub swrite { croak "usage: swrite PICTURE ARGS" unless @_; my $format = shift; $^A = ""; formline($format,@_); return $^A; } $string = swrite(<<'END', 1, 2, 3); Check me out @<<< @||| @>>> END print $string;

    These or found in perl manpages .

    Thanks SasiKumar
      Thanks! I read this. But I definetively missed the point.
Re: Perl formats without file handles
by blazar (Canon) on Feb 11, 2005 at 11:57 UTC
    I think that the other answers you got are definitely more on-topic wrt your question, but I'd like to mention that while I've never used formats myself nor did I think they were much used any more I've heard that there's an OO module by Damian Conway to use instead, that incidentally in the (IMHO authoritative) opinion of who supplied this piece of info provides additional functionality. Now, chances are that this may give you what you need straight out of the box...