Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling perl subroutines from the command line

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

like image 213
Mitchk Avatar asked Apr 13 '14 04:04

Mitchk


2 Answers

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
like image 188
mob Avatar answered Sep 22 '22 06:09

mob


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
like image 34
Dave Cross Avatar answered Sep 24 '22 06:09

Dave Cross