从命令行调用Perl子例程

8

好的,我想知道如何从命令行调用Perl子例程。如果我的程序叫做test,子例程叫做fields,我想通过命令行调用它。

test fields


我认为你需要给出test的内容示例。 - Borodin
5个回答

10

可以查看brian d foy的modulino模式,将Perl文件同时作为其他脚本可以使用的模块和独立程序进行处理。以下是一个简单的示例:

# Some/Package.pm
package Some::Package;
sub foo { 19 }
sub bar { 42 }
sub sum { my $sum=0; $sum+=$_ for @_; $sum }
unless (caller) {
    print shift->(@ARGV);
}
1;

输出:

$ perl Some/Package.pm bar
42
$ perl Some/Package.pm sum 1 3 5 7
16

这是过度杀伤力了,因为我们并不真正知道OP在想什么。 - Borodin
2
除非调用者,否则print shift->(@ARGV)是否过度了? - mob
shift->(@ARGV) 可以满足原帖问题的这种解释,但我认为我们还有很长的路要走才能理解需要什么。无论如何,对于一个有趣的参考,给予加一分。 - Borodin

9
使用调度表。
#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

sub fields {
  say 'this is fields';
}

sub another {
  say 'this is another subroutine';
}

my %functions = (
  fields  => \&fields,
  another => \&another,
);

my $function = shift;

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

一些例子:
$ ./dispatch_tab fields
this is fields
$ ./dispatch_tab another
this is another subroutine
$ ./dispatch_tab xxx
There is no function called xxx available

5

除非子程序是Perl内置的操作符,否则您无法这样做,例如sqrt,此时您可以编写

perl -e "print sqrt(2)"

或者如果它是由一个已安装的模块提供的,比如List::Util,就像这样:

perl -MList::Util=shuffle -e "print shuffle 'A' .. 'Z'"

这似乎是在无法修改Perl模块本身时使用的最佳(唯一?)解决方案。我发现了一些值得提及的注意事项:1. 您仍然可以在未安装的模块上运行此操作(即:临时Perl脚本),但您必须在模块所在的目录中,并且必须首先设置PERL_USE_UNSAFE_INC = 1。2. 这不适用于有状态子例程(即:依赖全局变量的方法或函数)。 - Alex Jansen

1

here is an example:

[root@mat ~]# cat b.pm 
#!/usr/bin/perl
#
#
sub blah {
    print "Ahhh\n";
}
return 1
[root@mat ~]# perl -Mb -e "blah";
Ahhh

0

不知道具体的要求,但这是一个解决方法,您可以在不需要太多修改代码的情况下使用。

use Getopt::Long;
my %opts;
GetOptions (\%opts, 'abc', 'def', 'ghi');
&print_abc    if($opts{abc});
&print_def    if($opts{def});
&print_ghi    if($opts{ghi});


sub print_abc(){print "inside print_abc\n"}
sub print_def(){print "inside print_def\n"}
sub print_ghi(){print "inside print_ghi\n"}

然后像这样调用程序:

perl test.pl -abc -def

请注意,您可以省略不需要的选项。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接