子程序作为数组成员

时间:2012-08-02 12:55:10

标签: perl

我可以将子例程作为其成员的Perl数组吗? 我有以下类型的子程序:

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

我想将这样的子程序添加到数组中,以便我可以迭代它并调用它们。

2 个答案:

答案 0 :(得分:10)

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

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

也可以传递参数:

$array[1]->( 'argument 1', 'argument 2' );

答案 1 :(得分: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!