perl - 如何将 @ARGV 的元素分配给 $variable,然后打印它?

标签 perl command-line-arguments argv string-interpolation

这个问题经常被各种方式问到,但是,我要再问一次,因为我没有完全理解@ARGV的应用,而且我还没有找到这个问题的答案(或者,更有可能的是,我不理解已经提供的答案和解决方案)。

问题是,为什么没有从命令行读取任何内容?另外,如何解密错误消息,

Use of uninitialised value $name in concatenation (.) or string at ... ?

据我所知,@ARGV 是一个存储命令行参数(文件)的数组。我也明白它可以像任何其他数组一样被操作(记住索引 $ARGV[0] 与文件名变量的命令行特性不同,$0).我知道在 while 循环中,菱形运算符会自动将 @ARGV 的第一个元素 shift$ARGV[ ],具有在输入处读取一行。

我不明白的是如何将 @ARGV 的元素分配给标量变量,然后打印数据。例如(取自 Learning Perl 的代码概念),

my $name = shift @ARGV;

while (<>) {
    print “The input was $name found at the start of $_\n”;
    exit;
}

就代码而言,$name 的输出是空白;如果我省略 shift()$name 会输出 0,我相信它应该在标量上下文中,但它不会回答为什么不接受来自命令行的输入的问题。我们将不胜感激您的见解。

谢谢。

最佳答案

my $name = shift @ARGV;确实分配程序的第一个参数。如果你得到 Use of uninitialised value $name in concatenation (.) or string at ... ,这是因为您没有为您的程序提供任何参数。

$ perl -we'my $name = shift(@ARGV); print "My name is $name.\n"'
Use of uninitialized value $name in concatenation (.) or string at -e line 1.
My name is .

$ perl -we'my $name = shift(@ARGV); print "My name is $name.\n"' ikegami
My name is ikegami.

<>绝对没问题之后。

$ cat foo
foo1
foo2

$ cat bar
bar1
bar2

$ perl -we'
   print "(\@ARGV is now @ARGV)\n";
   my $prefix = shift(@ARGV);

   print "(\@ARGV is now @ARGV)\n";
   while (<>) {
      print "$prefix$_";
      print "(\@ARGV is now @ARGV)\n";
   }
' '>>>' foo bar
(@ARGV is now >>> foo bar)
(@ARGV is now foo bar)
>>>foo1
(@ARGV is now bar)
>>>foo2
(@ARGV is now bar)
>>>bar1
(@ARGV is now )
>>>bar2
(@ARGV is now )

关于perl - 如何将 @ARGV 的元素分配给 $variable,然后打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64636640/

相关文章:

windows - 如何在 GUI 中显示 Perl 控制台输出?

java - 启动 java 程序时出现 ArrayIndexOutOfBoundsException

c - 如何解析不同类型的参数?

c - 如何验证 ARGV 中的 key ?

python-3.x - python新手,想了解argv语法

regex - 如何在 Perl 中提取并打印这些命名捕获组?

perl - 为什么我从 Perl 的 system() 开始的进程不是子进程?

perl - 用 Perl 构建专业应用程序?

bash - 如何将带有管道符号的多个参数传递到 bash 脚本 case 语句中

c - 将 argv 给出的内存地址分配给 c 中的指针