Reputation: 107
Ok so i was wondering how i would go about calling a perl subroutine from the command line. So if my program is Called test, and the subroutine is called fields i would like to call it from the command line like.
test fields
Upvotes: 8
Views: 15008
Reputation: 118605
Look into brian d foy's modulino pattern for treating a Perl file as both a module that can be used by other scripts or as a standalone program. Here's a simple example:
# 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;
Output:
$ perl Some/Package.pm bar
42
$ perl Some/Package.pm sum 1 3 5 7
16
Upvotes: 10
Reputation: 69244
Use a dispatch table.
#!/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";
}
Some examples:
$ ./dispatch_tab fields
this is fields
$ ./dispatch_tab another
this is another subroutine
$ ./dispatch_tab xxx
There is no function called xxx available
Upvotes: 9
Reputation: 1448
Dont know the exact requirements, but this is a workaround you can use without much modifications in your code.
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"}
and then call the program like :
perl test.pl -abc -def
Note that you can omit the unwanted options.
Upvotes: 0
Reputation: 126722
You can't do that unless the subroutine is a built-in Perl operator, like sqrt
for instance, when you could write
perl -e "print sqrt(2)"
or if it is provided by an installed module, say List::Util
, like this
perl -MList::Util=shuffle -e "print shuffle 'A' .. 'Z'"
Upvotes: 5
Reputation: 1099
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
Upvotes: 1