Perl将参数传递给Bash中的文件

时间:2017-07-02 03:27:15

标签: bash perl arguments

我必须在Perl文件中运行一个函数,并将参数传递给函数。

# program.pm

sub go
{
   # I need to use arguments here
   # print foo
   # print bar
}

my %functions = (
  go  => \&go
);

my $function = shift;

if (exists $functions{$function}) {
  $functions{$function}->();
} else {
  die "There is no function called $function available\n";
}

这需要运行并通过bash传递。我需要能够随机指定args,如下所示:

$ perl program.pm go foo='bar' bar='fubar'

我对Perl非常不熟悉。我正在谷歌搜索,不能为我的生活弄清楚如何正确解析这些。似乎有4种不同的方法可以做到,似乎没有一种方法适合我的用例。

我试过这个也无济于事。:

$ perl program.pm -e 'go(foo=>"bar")'

2 个答案:

答案 0 :(得分:4)

你已经接受的答案似乎相当复杂。只需对现有代码进行一些更改即可实现此目的。

sub go
{
   # I need to use arguments here
   # print foo
   # print bar
   print "In go\nArgs are: @_\n";
}

my %functions = (
  go  => \&go
);

my $function = shift;

if (exists $functions{$function}) {
  # Pass remaining command-line args to the called subroutine
  $functions{$function}->(@ARGV);
} else {
  die "There is no function called $function available\n";
}

我在print()中进行了go()调用(所以我知道它正在被调用)并且我已将@ARGV传递给调度表中的子例程。

你可以像任何其他Perl程序一样调用它。

$ perl program.pm go foo=bar bar=fubar
In go
Args are: foo=bar bar=fubar

$ perl program.pm XX foo bar
There is no function called XX available

更新:在评论中,添加了此要求:

  

但我如何将值拆分为哈希值?

这有两个答案。你选择哪一个取决于你真正想要做的事情。

如果您只想获取任何“foo = bar”字符串并将其解析为存储在哈希中的键/值对,则可以使用以下代码替换go()子例程:

use Data::Dumper;

sub go
{
   # I need to use arguments here
   # print foo
   # print bar

   my %args = map { split /=/ } @_;

   print "In go\nArgs are: " . Dumper(\%args) . "\n";
}

然后你得到这个输出:

$ perl program.pm go foo=bar bar=fubar
In go
Args are: $VAR1 = {
          'bar' => 'fubar',
          'foo' => 'bar'
        };

如果您实际上正在尝试解析命令行选项,那么您应该使用命令行选项解析器,如GetOpt::Long

use Data::Dumper;
use Getopt::Long 'GetOptionsFromArray';

sub go
{
   # I need to use arguments here
   # print foo
   # print bar

   my %args;

   GetOptionsFromArray(\@_, \%args, 'foo=s', 'bar=s');

   print "In go\nArgs are: " . Dumper(\%args) . "\n";
}

请注意,要使其正常工作,您需要传递以--开头的正确的Unix风格选项。

$ perl program.pm go --foo=bar --bar=fubar
In go
Args are: $VAR1 = {
          'bar' => 'fubar',
          'foo' => 'bar'
        };

但是这个版本的输入要求更加灵活:

$ perl program.pm go --f bar --b fubar
In go
Args are: $VAR1 = {
          'bar' => 'fubar',
          'foo' => 'bar'
        };

它会告诉您是否使用了无效的选项名称。

$ perl program.pm go --fu=bar --baz=fubar
Unknown option: fu
Unknown option: baz
In go
Args are: $VAR1 = {};

答案 1 :(得分:1)

您可以使用 $(this).flipcountdown({ size:'sm', beforeDateTime: $(this).attr('data-time-end') }); 将“program.pm”“包含”到“一个班轮”中。

shell / bash脚本

require

program.pm

perl -e 'require "/path/program.pm" ; &go(1=>2)'