Calling perl subroutines from the command line

前端 未结 5 1351
情深已故
情深已故 2020-12-18 04:13

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 lik

相关标签:
5条回答
  • 2020-12-18 04:55

    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.

    0 讨论(0)
  • 2020-12-18 05:09

    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
    
    0 讨论(0)
  • 2020-12-18 05:11

    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'"
    
    0 讨论(0)
  • 2020-12-18 05:14

    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
    
    0 讨论(0)
  • 2020-12-18 05:16

    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 讨论(0)
提交回复
热议问题