perl - 如果我在此之前阅读用户输入,为什么 perl 不能就地编辑工作?

标签 perl inplace-editing

我正在尝试在 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/

相关文章:

perl - 是否有可能在 EV 回调中使用 Perl 进行 longjump 之类的操作?

perl - 如何使用 WWW::Mechanize 保存图像的宽度、高度和字节?

windows - 如何将 Windows 命令提示符下发出的命令的 Perl 脚本输出重定向到文本文件

ruby-on-rails-3 - Rails-使用 best_in_place gem 就地编辑模型本身定义的数组集合

ruby - 如何使用 Ruby 的命令行就地编辑模式从文本文件中删除行

perl - 使用 Try::Tiny 还是 Eval?

perl - Perl 中带有导出器的多个包

eclipse - Eclipse 中所选单词的括号

macos - sed -i 命令用于就地编辑,可与 GNU sed 和 BSD/OSX 一起使用