Search code examples
perlcallbackperl-data-structures

perl using coderef as parameter to subroutine


I have the following subroutines:

sub my_sub {
    my $coderef = shift;    
    $coderef->();
}


sub coderef {
    my $a = shift;
    my $b = shift;

    print $a+$b;
}

and want to call my_sub(\coderef($a,$b)) in this manner i.e I want to provide the arguments of the code ref with it and run it on the my_sub function. Is it possible to do something like this in perl?


Solution

  • If those subs are to be taken at face value, my_sub isn't doing anything.

    There are two things going on here:

    1. Define the coderef

      my $adder = sub { my ( $first, $second ) = @_; $first + $second };
      
      # Adds first two arguments
      
    2. Execute it with the necessary parameters

      print $adder->(2,3);  # '5'
      

    Assuming my_sub is some kind of a functor that is passed the coderef as its first argument:

    sub functor {
        my $coderef = shift;  # Pull of first argument
        $coderef->( @_ );     # Rest of @_ are coderef arguments
                              # Or simply : sub functor { +shift->( @_ ) }
    }
    
    # Usage:
    
    print functor ( $adder, 2, 3 );  # '5'