regex - 将输出打印到 perl 中的文件

标签 regex perl file-io stdout

我一直在尝试查找与文件处理相关的示例,但没有找到任何可以解决我的问题的内容。

    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/

相关文章:

Python re.finditer() : concisely detect "A or :B or C:D"

perl - 如何将 "lazy load"包用作委托(delegate)?

perl - 使用 Perl Text::CSV 从数据库写入

java - 延迟处理客户端数据: Treat java socket id as a file id

c++ - boost interprocess file_lock不适用于多个进程

java - 如何从文件中读取大的 clob 数据?

c# - .NET : StreamReader does not recognize ° characters

javascript - 使用正则表达式过滤 url 中的问号 (?) 参数并添加 ?或者 &

c - 如何用C语言在文件的特定位置写入字符串

Java 字符串 ReplaceAll 和 ReplaceFirst 在替换文本的 $ 符号处失败