Is there a way to capture a subroutine's print output to a variable so I can send it to stderr instead?

后端 未结 4 1024
离开以前
离开以前 2021-01-12 08:50

Suppose we have:

sub test {
        print \"testing\\n\";
}

If there is a case where I want to have it print to stderr instead of stdout, i

4条回答
  •  被撕碎了的回忆
    2021-01-12 09:00

    Meanwhile, you can also "capture a subroutine's print output to a variable."

    Just pass a scalar ref to open:

    #! /usr/bin/env perl
    use common::sense;
    use autodie;
    
    sub tostring (&) {
      my $s;
      open local *STDOUT, '>', \$s;
      shift->();
      $s
    }
    
    sub fake {
      say 'lalala';
      say 'more stuff';
      say 1 + 1, ' = 2';
      say for @_;
    }
    
    for (tostring { fake(1, 2, 3) }) {
      s/\n/\\n/g;
      say "Captured as string: >>>$_<<<";
    }
    

    Output:

    Captured as string: >>>lalala\nmore stuff\n2 = 2\n1\n2\n3\n<<<
    

提交回复
热议问题