If I have a program called simplecalc.pl
:
use v5.10;
use warnings;
use strict;
# SIMPLE CALCULATOR
# Usage: simplecalc.pl <n1> <n2> [<verbose> <logswitch>]
# Example Usage:
# normal usage : simplecalc.pl 4 2
# verbose usage : simplecalc.pl 4 2 1
# support-case usage: simplecalc.pl 4 2 0 1
my($OK,$UNKNOWN)=(0,3);
my($filename, $endmsg, $exit) = ('my.log', undef, undef);
my($n1, $n2, $DEBUG, $GET_SUPPORT_FILE) = @ARGV;
# Handling of the support-file starts here ===============================
*ORIGINAL_STDOUT = *STDOUT;
if ($GET_SUPPORT_FILE) {
$DEBUG = 1;
$endmsg = "support-info sucessfully written into $filename";
$exit = $UNKNOWN;
# redirect stdout and stderr
open my $stdout_txt, '>>:utf8', "$filename";
*STDOUT = $stdout_txt;
open STDERR, '>&STDOUT';
} else {
$endmsg = "Finnished calculation - good bye.";
$exit = $OK;
}
END {
select *ORIGINAL_STDOUT;
say $endmsg;
};
# end of support-file handling ============================================
say STDERR "INFO: got $n1 and $n2 from the commandline" if $DEBUG;
say "Hello, let me calc the quotient from $n1 trough $n2 for you ...";
my $quotient = $n1 / $n2;
say "Quotient: $quotient";
exit $exit;
Is there a way to put the lengthy handling of the support-file in a reusable way into a module? (The support-file is meant to be sent by the user to the program-maintainer.)
Note: The above solution also works for simplecalc.pl 4 0 0 1
which results in a division trough 0. Catching a die
in any module used by the main-programm and write the die-msg into the support-file is an important feature.
get_support
it once redirects streams (and doesn't write anything?) but the other time it switches back. In the desired-module, I don't see what thewrite_support_file
writes to that file (there is only the message for the restoredSTDOUT
). Can you state the purpose? – Adel