Thursday, April 22, 2010

Callback function in Perl: EG

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

my $adder = sub {
my ( $arg1, $arg2 ) = @_;
return $arg1 + $arg2;
};

my $multiplier = sub {
my ( $arg1, $arg2 ) = @_;
return $arg1 * $arg2;
};

sub doit {
my ($action, $arg1, $arg2) = @_;
return $action->( $arg1, $arg2 );
}

# This returns 30
my $val1 = doit( $adder, 10, 20 );

# This returns 200
my $val2 = doit( $multiplier, 10, 20 );

No comments: