jeberle
jeberle

Reputation: 758

Is there a quick way to redirect output in Perl?

In Perl this takes 6 lines:

my $rpt = 'report.txt';
open my $f, '>', $rpt or die "$0: cannot open $rpt: $!\n";
select $f;
print_report($a, $b, $c);
close $f;
select STDOUT;

In Bash this takes 1 line:

print_report $a $b $c >report.txt

Is there a way to trim down the Perl code?

Upvotes: 0

Views: 143

Answers (3)

Julian Fondren
Julian Fondren

Reputation: 5619

#! /usr/bin/env perl
use common::sense;

sub into (&$) {
  open my $f, '>', $_[1] or die "$0: cannot open $_[1]: $!";
  my $old = select $f;
  $_[0]->();
  select $old
}

sub fake {
  say 'lalala';
  say for @_;
}

say 'before';
into { fake(1, 2, 3); say 4 } 'report.txt';
say 'after';

Usage:

$ perl example
before
after
$ cat report.txt
lalala
1
2
3
4

Upvotes: 1

mpapec
mpapec

Reputation: 50637

Simple redirect if you don't need to restore STDOUT

my $rpt = 'report.txt';
open STDOUT, '>', $rpt or die "$0: cannot open $rpt: $!\n";
print_report($a, $b, $c);

Upvotes: 3

Evan Carroll
Evan Carroll

Reputation: 1

That's because you're cheating. You don't have to store the report name in a variable, select the filehandle, or close it, to print to a file...

open my $fh, '>', 'report.txt' or die "$0: cannot open $fh: $!\n";
print $fh func($a, $b, $c);

Alas, per mob if you want to redirect STDOUT use shell redirection. If you don't want STDOUT to default to the terminal, it makes sense to change it where the default cascades to the program,

perl script_that_runs_print_report.pl > report.txt

Upvotes: 7

Related Questions