如何在cmd行参数中传递数组的索引,这是函数指针并调用perl中的特定函数?

时间:2020-12-05 21:25:24

Suppose I have 2 functions in Perl. I would create a array of references of that two functions. & in command line argument I'll pass only that index of array which call specific function and if I don't give any argument then it'll call all functions which referenced were in array(Default case).

假设我在Perl中有2个函数。我会创建这两个函数的引用数组。 &在命令行参数中我只传递调用特定函数的数组索引,如果我不给出任何参数,那么它将调用引用的所有函数都在数组中(默认情况)。

So, can any help me to do this?

那么,有什么可以帮助我做到这一点?

## Array content function pointers
my @list= {$Ref0,$Ref1 }


my $fun0Name = “fun0”;
my $Ref0 =&{$fun0Name}();

my $fun1Name = “fun1”;
my $Ref1 =&{$fun1Name}();

#### Two functions

sub fun0() {
   print "hi \n";
}

sub fun1() {
   print "hello \n";
}

##### Now in cmd argument if i passed Test.pl -t 0(index of array ,means call to 1st function)
##### if i give test.pl -t (No option ) ....then i call both function. 

1 个解决方案

#1


2  

Creating a function pointer (called a code reference in Perl) is easy enough:

创建一个函数指针(在Perl中称为代码引用)很容易:

sub foo { 
    say "foo!";
}

sub bar { 
    say "bar!";
}

my $foo_ref = \&foo;
my $bar_ref = \&bar;

Putting things in an array is pretty easy:

将事物放入数组非常简单:

my @array = ( $foo_ref, $bar_ref );

Reading arguments from the command line is pretty easy:

从命令行读取参数非常简单:

my $arg = shift @ARGV;

Looking things up in an array is also pretty easy:

在数组中查找内容也非常简单:

my $item = $array[$arg];

Which part are you having trouble with?

你遇到哪个问题?

#1


2  

Creating a function pointer (called a code reference in Perl) is easy enough:

创建一个函数指针(在Perl中称为代码引用)很容易:

sub foo { 
    say "foo!";
}

sub bar { 
    say "bar!";
}

my $foo_ref = \&foo;
my $bar_ref = \&bar;

Putting things in an array is pretty easy:

将事物放入数组非常简单:

my @array = ( $foo_ref, $bar_ref );

Reading arguments from the command line is pretty easy:

从命令行读取参数非常简单:

my $arg = shift @ARGV;

Looking things up in an array is also pretty easy:

在数组中查找内容也非常简单:

my $item = $array[$arg];

Which part are you having trouble with?

你遇到哪个问题?