【发布时间】:2025-11-29 05:05:01
【问题描述】:
如果我有一个名为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;
有没有办法将支持文件的冗长处理以可重用的方式放入模块中? (支持文件是由用户发送给程序维护者的。)
注意:上述解决方案也适用于simplecalc.pl 4 0 0 1,这会导致除法槽 0。在主程序使用的任何模块中捕获die 并将 die-msg 写入支持文件是很重要的功能。
【问题讨论】:
-
我看不到您需要什么——在
get_support下,它曾经重定向流(并且什么都不写?)但其他时候它又切换回来。在期望的模块中,我看不到write_support_file写入该文件的内容(只有恢复的STDOUT的消息)。你能说明目的吗? -
你说得对,问题的措辞和布局都不是最佳的。我将使用@kjetil-s 答案中的元素重写它。
-
谢谢,清楚多了。我仍然不确定总体目的,请查看我的答案,如果需要,请告诉我