Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Writing formatted text to a string?

by loris (Hermit)
on May 16, 2011 at 12:12 UTC ( #905054=perlquestion: print w/replies, xml ) Need Help??
loris has asked for the wisdom of the Perl Monks concerning the following question:

OK, after having asked about Placement of $~ or $FORMAT_NAME I've learnt somethingabout select(), but also that I was asking the wrong question.

I have a program that a naughty user can run and which uses format to produce a list of his or her acts of naughtiness on the console. Strangely, naughty users don't seem to run this program themselves very often. So I would like to run it myself and, if I feel that the user has been sufficiently naughty, send him or her the output of the program in an email.

For this I would like to able to print the formatted data either to the console or to a string. I could then pass the string as a message body to some thing like MIME::Lite. I can do the former, but for the latter the best I can come up with would be to write to a file and then read the contents of the file to a string.

Is there a less clunky alternative?



Replies are listed 'Best First'.
Re: Writing formatted text to a string?
by JavaFan (Canon) on May 16, 2011 at 12:43 UTC
    open my $fh, ">", \my $string_to_write_to or die "...";

      Just to remind myself: The backslash in open($fh, '>', \$variable) allows the filehandle to be opened to an "in memory" file held in a scalar. See open.


      Here is my working example:

      #!/usr/bin/perl use strict; use warnings; use English qw( -no_match_vars ); use Getopt::Long; my $in_memory; GetOptions('in_memory|i' => \$in_memory, ); my $greeting = "Hello World!"; format BLAH = Greeting: @<<<<<<<<<<<<<<<< $greeting . my $fh; my $message; if (defined($in_memory)) { open $fh, '>', \$message or die "Couldn't open for writing: $!"; } else { $fh = *STDOUT; } select($fh); $FORMAT_NAME = 'BLAH'; write(); select(STDOUT); if (defined($in_memory)) { print "Message written to in memory variable:\n"; print "$message"; close($fh); }


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://905054]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2018-02-24 13:01 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (310 votes). Check out past polls.