3

我可以拥有一个以子例程为成员的 Perl 数组吗?我有以下类型的子程序:

sub CheckForSprintfUsage {
  my ($line, $fname, $linenum) = @_;  
  if ( $line =~ /\bsprintf\b/ ) {
    printError((caller(0))[3],$fname,$linenum);
  }
}

我想将这样的子例程添加到一个数组中,以便我可以遍历它并调用它们。

4

2 回答 2

10

将对子例程的引用插入到数组中:

my @array = (
    \&foo,
    \&bar,
    sub {
        # Do something inside anonymous subroutine
    },
    \&CheckForSprintfUsage,
);
$array[1]->();  # Call subroutine `bar`

也可以传递参数:

$array[1]->( 'argument 1', 'argument 2' );
于 2012-08-02T13:01:29.040 回答
3

是的。你可以在 Perl 中引用任何你想要的东西,所以你可以有一个 Perl 函数数组。

#! /usr/bin/env perl

use strict;
use warnings;

my @array;

sub foo {
    my $name = shift;
    print "Hello $name, I am in foo\n";
}   

# Two ways of storing a subroutine in an array

# Reference to a named subroutine
$array[0] = \&foo;  #Reference to a named subroutine

# Reference to an unnamed subroutine
$array[1] = sub {   #Reference to an anonymous subroutine
    my $name = shift;
    print "Whoa $name, This subroutine has no name!\n";
};  

# Two ways of accessing that subroutine

# Dereference using the "&"
&{$array[0]}("Bob"); #Hello Bob, I am in foo

# Using Syntactic sugar. Really same as above
$array[1]->("Bob");  #Whoa Bob, This subroutine has no name!
于 2012-08-02T13:22:19.613 回答