Calling perl routines from the command line

Ok, so I was wondering how I would access the perl routine from the command line. Therefore, if my program is called the Called Test, and the routine is called the fields that I would like to call from the command line, for example.

test fields

+4
source share
5 answers

Use the mailing 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
+3
source

See the Brian d foy modulino pattern for processing a Perl file as a module that can be used by other scripts or as a standalone program. Here is 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
+6
source

, Perl, sqrt,

perl -e "print sqrt(2)"

, List::Util,

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

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
source

I don’t know the exact requirements, but this is a workaround that you can use without significant changes to 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 as follows:

perl test.pl -abc -def

Please note that you may omit unwanted parameters.

0
source

Source: https://habr.com/ru/post/1536294/


All Articles