Perl 尊重 '<'作为常规字符而不是输出重定向 [英] Perl is respecting '<' as a regular character rather an output redirection
问题描述
我需要一些帮助来解决这个特定的编码问题.
I would like some help figuring this particular coding problem.
我有一个调用另一个 perl 脚本(#2)的 perl 脚本(#1).在#1 中,我调用#2 也将其输出重定向到日志文件.像这样
I have a perl script (#1) that calls another perl script(#2). In #1, I call #2 to also redirect its output to a log file. like so
my @command = ('downloadImage', '-url', $url, '>', $log);
此命令在终端上运行时运行良好.我是否必须使用其他类型的特殊字符来告诉 perl > 是输出重定向,而不仅仅是一些常规字符?
this commands runs fine when it runs on the terminal. Do I have to use some other kind of special character to tell perl that > is output redirection not just some regular character?
我运行它:
system(@command);
推荐答案
我假设完整的代码是:
my @command = ('downloadImage', '-url', $url, '>', $log);
system @command;
system
有两种模式.system $command
将在 shell 中运行 $command
.
system
has two modes. system $command
will run $command
in the shell.
# This will write 'foo' to the file 'bar'
system "echo foo > bar";
system @command
实际上是 system $program, @args
.它将绕过 shell 并使用 @args
运行 $program
.
system @command
is really system $program, @args
. It will bypass the shell and run the $program
with @args
.
# This will print 'foo > bar'
system "echo", "foo", ">", "bar"
所以如果你想像这样进行输出重定向,你可以将@command 连接在一起.
So if you want to do output redirection like that you could join @command together.
system join " ", @command;
但这可能会遇到 shell 引用问题.在 Perl 中使用 管道打开自己进行重定向更安全、更快、更便携.
But that can run into shell quoting issues. It's safer, faster, and more portable to do the redirection yourself in Perl using a piped open.
use strict;
use warnings;
use autodie;
open my $echo, "-|", "echo", "foo";
open my $log, ">", "some.log";
print {$log} <$echo>;
这篇关于Perl 尊重 '<'作为常规字符而不是输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!