perl - 如何将@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
,正如我认为应该的那样,在标量上下文中,但它没有回答为什么命令行输入不被接受的问题。您的见解将不胜感激。
谢谢你。
解决方案
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 )
推荐阅读
- html - 向“复选框”输入类型添加溢出滚动条
- pyqt5 - PyQt5 - 获取 QWidget 内的像素颜色
- python - How to iterate over a python dictionary, setting the key of the dictionary as another dictionary's value
- python - pyspark dataframe: remove duplicates in an array column
- fflush - abrupt end of program while fflush in c
- mysql - mysql的过滤子句语法
- javascript - 使用JS在json中的偶数和奇数元素之间交替
- angular - 在按钮单击时导航到 p-tabview
- android - 在 FireMonkey Android 应用程序中关闭一个控件的虚拟键盘
- python - 使用 python 将图像转换为具有透明背景的 tiff 格式