简体   繁体   English

从perl脚本内部可以知道要将输出重定向到的文件的名称吗?

[英]From inside a perl script can you know the name of the file you are redirecting output to?

So I have: 所以我有:

test.pl > test.log

is there a way to know inside test.pl that I am outputing to 'test.log'? 有没有办法知道我在输出'test.log'的test.pl里面? At the end of my script I want to do some manipulation of test.log without hardcoding the name. 在我的脚本结束时,我想对test.log进行一些操作而不用硬编码名称。

Maybe. 也许。 The following works on Linux, but will not be very portable to other systems... 以下适用于Linux,但不会对其他系统非常便携......

#!/usr/bin/env perl

use strict;
use warnings;

my $out = readlink("/proc/$$/fd/1");
print STDERR "I am being output to $out\n";

Naturally, this is probably a bad idea. 当然,这可能是一个坏主意。 Better to explicitly open the file and write to it in Perl, rather than having the shell set up redirections. 最好显式打开文件并在Perl中写入它,而不是让shell设置重定向。

You can redirect standard output from perl, with minimal changes to your script, 您可以从perl重定向标准输出,只需对脚本进行最少的更改,

test.pl test.log

my ($file) = @ARGV;
if (@ARGV) {
  open STDOUT, ">", $file or die $!;
}

print "output is redirected to $file\n";

# use $file at the end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM