Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
smith Avatar asked Feb 12 '26 15:02

smith


1 Answers

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'
like image 103
Zaid Avatar answered Feb 15 '26 07:02

Zaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!