我一直在尝试查找与文件处理相关的示例,但没有找到任何可以解决我的问题的内容。
use strict;
use warnings;
my ($m, $b) = @ARGV;
my $count_args = $#ARGV + 1;
my $times = 2**$m;
my $output = "main fucntion to be called???\n";
open(OUTFILE, "> output1.txt") || die "could not open output file";
print OUTFILE "$output\n"; ## Notice, there is not a comma after the file handle and the string to be output
close(OUTFILE);
main();
sub main {
if ($m =~ /^\d+$/) {
if ($b =~ /^and$/i) {
func_and();
}
else {
print " not supported\n";
}
}
else {
print " enter valid number of pins\n";
}
}
sub func_and {
my $bit;
for (my $i = 0 ; $i < $times ; $i++) {
my $p = sprintf("%0${m}b", $i);
print "$p\t";
my @c = split('', $p);
my $result = 100;
foreach $bit (@c) {
if ($result < 100) {
$result = $result && $bit;
}
else {
$result = $bit;
}
}
print "result is $result \n";
}
}
如果我提供输入 2 并且输出打印在屏幕上,则该程序将打印输出。
我想更改该程序的文件句柄STDOUT
,即我想将输出打印到output1.txt文件
您能指出我犯的错误吗? ----->
将 STDOUT 复制到另一个文件句柄
open (my $STDOLD, '>&', STDOUT);
# redirect STDOUT to log.txt
open (STDOUT, '>>', "$ARGV[1]".".log");
print main();
# restore STDOUT
open (STDOUT, '>&', $STDOLD);
print " check .log file\n This should show in the terminal\n";
这对我有用..但是在日志文件的末尾我打印了数字“1”我不知道为什么..我相信这是正在打印的时间戳。我需要删除它..你知道为什么会发生吗?
最佳答案
听起来您想将程序的输出重定向到文件?
要从命令行执行此操作,请输入
perl myprogram.pl > myoutput.txt
如果您希望打印到 STDOUT
的所有内容都转到文件中,那么只需在程序开始时将其作为文件句柄打开即可。
像这样
open STDOUT, '>', 'myoutput.txt' or die $!;
关于regex - 将输出打印到 perl 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212043/