1

I am new in Perl. I just need to send a general function that takes two parameters to another function and then call the first function from inside the second function. I am not very sure how that can be done. Here is the code I am trying to write.

sub add { return $_[0] + $_[1]; }
sub subt { return $_[0] - $_[1]; }

sub dosth
{
    my ($func, $num0, $num1) = @_;
    # how to call code $func with arguments $num0 and $num1 and return the return value of $func
}

print dosth(add, 3, 2) . " " . dosth(subt, 3, 2); # desired output: 5 1

1 Answer 1

7

Like this:

sub add { return $_[0] + $_[1]; }
sub subt { return $_[0] - $_[1]; }

sub dosth {
    my ($func, $num0, $num1) = @_;
    return $func->($num0, $num1);
}

print dosth(\&add, 3, 2) . " " . dosth(\&subt, 3, 2); # 5 1

Online at http://codepad.org/RX1auCRn

The trick is to pass references to the subroutine to dosth, then you can call indirectly with the arrow.

Sign up to request clarification or add additional context in comments.

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.