如何解决如何使用unix shell中的参数调用子例程
我正在使用Perl脚本的不同子例程。 可以通过Unix shell从Perl脚本中调用单个子例程,例如:
简化示例:
perl automated_mailing.pl inf
然后调用inform_user
中的函数automated_mailing.pl
。
这是通过调度表实现的:
my %functions = (
inf=> \&inform_user,);
inform_user
看起来
sub inform_user{
print "inform user: Angelo";
...some other stuff...
}
现在的问题是,如何用一个变量替换“ Angelo”并从shell中调用它,如:
sub inform_user{
my ($to)=@_;
print "inform user: $to";
}
此呼叫无效:
perl automated_mailing.pl inf("Brian")
这如何正确完成?
解决方法
-
您需要将参数作为单独的命令行参数传递:
perl automated_mailing.pl inf Brian
-
您需要将命令行参数传递给您调用的子例程:
my ($func,@args) = @ARGV; # And then later... if (exists $functions{$func}) { $functions{$func}->(@args); } else { die "$func is not a recognised function\n"; }
您还没有显示出实际使用调度表的代码-所以我的第二点是一些猜测。
,有了给定的提示,我完全达到了我想要的。 程序现在看起来像:
use warnings;
use strict;
sub inform_user{
my @to = @ARGV;
print "inform user: $to[0]";
}
my %functions = (
inform_user=> \&inform_user,);
my $function = shift;
if (exists $functions{$function}) {
$functions{$function}->();
} else {
die "There is no function called $function available\n";
}
,输出为:
>> perl automated_mailing.pl inf Brian
>> inform user: Brian
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。