Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how do I pass a function as argument of another function?

I wrote the following Perl Class:

package Menu;
use strict;

my @MENU_ITEMS;
my $HEADER = "Pick one of the options below\n";
my $INPUT_REQUEST = "Type your selection: ";

sub new {
    my $self = {};
   $self->{ITEM}   = undef;
   $self->{HEADER} = undef;
   $self->{INPUT_REQUEST} = undef;
   bless($self);
   return $self;
}

sub setHeader {
    my $self = shift;
    if(@_) { $self->{HEADER} = shift }
    $HEADER = $self->{HEADER}."\n";
}

sub setInputRequest {
    my $self = shift;
    if(@_) { $self->{INPUT_REQUEST} = shift }
    $INPUT_REQUEST = $self->{INPUT_REQUEST}." ";
}

sub addItem {
    my $self = shift;
    if(@_) { $self->{ITEM} = shift }
    push(@MENU_ITEMS, $self->{ITEM}); 
    }

sub getMenu {
    my $formatted_menu .= $HEADER;
    my $it=1;
    foreach(@MENU_ITEMS) {
        $formatted_menu.=$it.". ".$_."\n";
        $it++
      }
    $formatted_menu.=$INPUT_REQUEST;
    return $formatted_menu;
}
1;

If I call the following perl script:

#!/usr/bin/perl
use strict;
use Menu;

my $menu = Menu->new();
$menu->addItem("First Option");
$menu->addItem("Second Option");
print $menu->getMenu;

I'll get the following output:

Pick one of the options below
1. First Option
2. Second Option
Type your selection:

I'd like to modify given class in a way that I can pass a second argument to the method addItem()

something like: $menu->addItem("First Option", &firstOptionFunction());

and if and only if First Option is selected, then $firstOptionFunction is executed.

Is there any way to achieve such behavior in Perl? Thanks!

like image 284
ILikeTacos Avatar asked May 09 '12 20:05

ILikeTacos


1 Answers

You would want to pass a reference to the subroutine.

$menu->addItem("First Option", \&firstOptionFunction);

And your addItem method might look like this:

sub addItem { ## your logic may vary
    my ( $self, $option, $code ) = @_;
    if ( $option eq 'First Option' ) {
        $code->();
    }

    $self->{ITEM} = $option;
    push @MENU_ITEMS, $option;

    return;
}

As you mentioned in the comments, you might want to not pass the subroutine as a reference, but rather store it somewhere else. Something like this might work:

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    $self->{f_o_code} = \&firstOptionFunction; ## use a better name than f_o_code
    return $self;
}

## add your other methods

sub addItem { ## your logic may vary
    my ( $self, $option ) = @_;
    if ( $option eq 'First Option' ) {
        $self->{f_o_code}->();
    }

    $self->{ITEM} = $option;
    push @MENU_ITEMS, $option;

    return;
} ## call like $menu->addItem( 'First Option' );
like image 145
gpojd Avatar answered Oct 17 '22 19:10

gpojd