Calling perl subroutines from the command line

前端 未结 5 1363
情深已故
情深已故 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 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
    

提交回复
热议问题