如何在命令行上将值传递给 Perl 子例程参数?
我的 test.pl 脚本如下。
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
sub printargs
{
print "@_\n";
}
&printargs("hello", "world"); # Example prints "hello world"
如果我用 print($a, $b);
替换 printargs("hello", "world");
。
当我在命令行运行 perl test.pl hello world 时,如何将 'hello' 、'world' 传递给 $a 、 $b ,谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请阅读 perldoc perlvar。
Do read about
@ARGV
in perldoc perlvar.$ARGV[0]包含第一个参数,$ARGV[1]包含第二个参数,以此类推。
$#ARGV是@ARGV数组最后一个元素的下标,因此命令行上的参数个数为$# ARGV + 1。
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
命令行参数位于@ARGV 数组中。只需将其传递给您的函数:
可能最好避免使用像
print
这样的名称 - 可能会与同名的内置函数混淆。The command-line arguments are in the
@ARGV
array. Just pass that to your function:Probably best to avoid a name like
print
- might get confused with the built-in function of the same name.您想要访问 Perl 中的“命令行参数”。
基本上,Perl 将您在实际脚本名称之后传递的字符串视为名为 @ARGV 的数组。
这是一个简短的教程: http://devdaily.com/perl/edu/qanda/ plqa00001.shtml
只需谷歌“perl 命令行参数”即可了解更多信息。
You want to access "command line parameters" in Perl.
Basically Perl sees the string you pass after the actual script name as an array named @ARGV.
Here is a brief tutorial: http://devdaily.com/perl/edu/qanda/plqa00001.shtml
Just google "perl command line parameters" for more.
基本上,正如其他人所说,@ARGV 列表就是您问题的答案。
现在,如果您想进一步为程序定义命令行选项,您还应该查看 getargs。
Basically, as others said, the @ARGV list is the answer to your question.
Now if you want to go further and define command lines options for your programs, you should also have a loog at getargs.
这还会从命令行参数打印“hello world”,同时根据请求将数据传递给 $a 和 $b。
This would also print "hello world" from the command line arguments while passing the data to $a and $b as requested.