Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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?

Thanks,

loris

Comment on Writing formatted text to a string?
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.

      Update:

      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); }

      loris

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://905054]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (9)
As of 2014-07-23 06:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (133 votes), past polls