【问题标题】:How to call subroutines with parameters from unix shell如何从 unix shell 调用带有参数的子例程
【发布时间】:2020-12-06 11:27:48
【问题描述】:

我正在使用 Perl 脚本的不同子例程。 可以通过 Unix shell 从 Perl 脚本调用单个子例程,例如:

简化示例:

perl automated_mailing.pl inf

然后调用来自automated_mailing.pl 的函数inform_user。 这是通过调度表实现的:

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 unix command-line


    【解决方案1】:
    1. 您需要将参数作为单独的命令行参数传递:

      perl automated_mailing.pl inf Brian
      
    2. 您需要将命令行参数传递给您调用的子例程:

      my ($func, @args) = @ARGV;
      
      # And then later...
      
      if (exists $functions{$func}) {
        $functions{$func}->(@args);
      } else {
        die "$func is not a recognised function\n";
      }
      

    您还没有显示实际使用调度表的代码 - 所以我的第二点有点猜测。

    【讨论】:

      【解决方案2】:

      有了给定的提示,我完全达到了我想要的。 程序现在看起来像:

      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
      
      

      【讨论】:

      • 我真的建议在调用 $functions{$function}->() 时将 @ARGV 作为参数传递,而不是在子例程中将其用作全局参数。
      猜你喜欢
      • 2017-02-26
      • 2018-12-27
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多