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

Den*_*Den 3 perl string-interpolation argv command-line-arguments

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

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

在连接 (.) 或 string at ... 中使用未初始化的值 $name ?

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

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

my $name = shift @ARGV;

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

就代码而言,$name的输出为空白;如果我省略shift()$name将输出0,正如我认为应该的那样,处于标量上下文中,但它没有回答为什么来自命令行的输入不被接受的问题。您的见解将不胜感激。

谢谢你。

ike*_*ami 5

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.
Run Code Online (Sandbox Code Playgroud)

<>以后用绝对没问题。

$ 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 )
Run Code Online (Sandbox Code Playgroud)