首页 > 解决方案 > 如何将@ARGV 的元素分配给$ 变量,然后打印它?

问题描述

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

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

在连接 (.) 或字符串 ... 中使用未初始化的值 $name?

我知道这@ARGV是一个存储命令行参数(文件)的数组。我也明白它可以像任何其他数组一样被操作(记住索引$ARGV[0]与文件名变量的命令行功能不同$0)。我知道在 while 循环中,菱形运算符将自动成为asshift的第一个元素,并在输入处读取一行。@ARGV$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,正如我认为应该的那样,在标量上下文中,但它没有回答为什么命令行输入不被接受的问题。您的见解将不胜感激。

谢谢你。

标签: perlcommand-line-argumentsargvstring-interpolation

解决方案


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 )

推荐阅读