如何将 @ARGV 的元素分配给 $variable,然后打印它?
How do I assign an element of @ARGV to a $variable, then print it?
这个问题经常被各种方式问到,但是,我要再问一次,因为我没有完全理解 @ARGV
的应用,因为我还没有找到这个问题的答案(或者,更有可能的是,我不理解已经提供的答案和解决方案。
问题是,为什么没有从命令行读取任何内容?另外,如何解密错误信息,
Use of uninitialised value $name in concatenation (.) or string at ... ?
我了解到@ARGV
是一个存储命令行参数(文件)的数组。我也明白它可以像任何其他数组一样被操作(记住索引 $ARGV[0]
与文件名变量 [=14=]
的命令行特性不同)。我知道在 while 循环中,菱形运算符会自动 shift
@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
,因为我相信它应该在标量上下文中,但它没有回答为什么命令行输入的问题也不被接受。您的见解将不胜感激。
谢谢。
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 )
这个问题经常被各种方式问到,但是,我要再问一次,因为我没有完全理解 @ARGV
的应用,因为我还没有找到这个问题的答案(或者,更有可能的是,我不理解已经提供的答案和解决方案。
问题是,为什么没有从命令行读取任何内容?另外,如何解密错误信息,
Use of uninitialised value $name in concatenation (.) or string at ... ?
我了解到@ARGV
是一个存储命令行参数(文件)的数组。我也明白它可以像任何其他数组一样被操作(记住索引 $ARGV[0]
与文件名变量 [=14=]
的命令行特性不同)。我知道在 while 循环中,菱形运算符会自动 shift
@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
,因为我相信它应该在标量上下文中,但它没有回答为什么命令行输入的问题也不被接受。您的见解将不胜感激。
谢谢。
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 )