我正在尝试在 perl 脚本中就地编辑 cfg 文件,但如果我在此之前读取用户输入,则它不起作用。这是一个测试脚本,用于重现我所看到的问题。
#!/usr/bin/perl -w
use strict;
my $TRACE_CFG = "trace.cfg";
print "Continue [y/N]> ";
my $continue = <>;
{
local $^I = '.bak';
local @ARGV = ($TRACE_CFG);
while (<>) {
s/search/replace/;
print;
}
unlink("$TRACE_CFG.bak");
}
如果我注释掉“my $continue = <>;”,则编辑有效线。如果我确实读取了用户输入,则似乎将 @ARGV 设置为 trace.cfg 文件不会生效并且 while 循环等待来自 STDIN 的输入。我可以通过使用 sed 或使用临时文件并重命名来解决这个问题,但我想知道这种行为的原因以及正确的方法。
最佳答案
根据 perlop
:
Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames.
You can modify @ARGV before the first <> as long as the array ends up containing the list of filenames you really want.
关于perl - 如果我在此之前阅读用户输入,为什么 perl 不能就地编辑工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559375/