Avinash
Avinash

Reputation: 13257

Subroutines as array members

Can I have a Perl array with subroutines as its members? I have subroutines of following type:

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

I want to add such subroutines into an array so that I can iterate over it and call them.

Upvotes: 3

Views: 1557

Answers (2)

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74242

Insert references to subroutines into arrays:

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

Arguments can be passed as well:

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

Upvotes: 10

David W.
David W.

Reputation: 107040

Yes. You can have references to ANYTHING you want in Perl, so you can have a Perl array of functions.

#! /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!

Upvotes: 3

Related Questions