3

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.

2 Answers 2

10

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' );
Sign up to request clarification or add additional context in comments.

Comments

3

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.