simont
simont

Reputation: 72637

call subroutine in print function

I've got a subroutine: calcPercentage. I want to print the value returned by this subroutine.

Can I do this in a single line, similar to this:

print "Result is: $calcPercentage($a,$b)"

Upvotes: 3

Views: 8336

Answers (4)

LeoNerd
LeoNerd

Reputation: 8532

I sometimes do this using a printf:

printf "Result is: %.2f\n", calcPercentage($a, $b)

Unrelatedly on a stylistic note, the usual naming convention in perl is under_scores not camelCase, and $a and $b are reserved variable names; usually in examples it's better to use $x and $y which are free.

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263457

The best way to do this is to pass the function call as one of the arguments to print, as the other answers say.

But if, for some reason, you want the result of a function call to be expanded inside a string literal, as "foo $bar" expands a variable name, there actually is a (rather ugly) way to do it:

print "Result is: @{[calcPercentage($a,$b)]}";

See this question.

Again, this is not particularly useful if you're just using print, since print itself concatenates its arguments. And even if you're not using print it's probably better just to concatenate the arguments yourself:

$s = "Result is: " . calcPercentage($a, $b);

Upvotes: 3

Vijay
Vijay

Reputation: 67291

> cat hello.pl
#!/usr/bin/perl

sub hello_p
{

return "hello"
}

print "return value is ",hello_p,"\n";

execution is below:

> perl hello.pl
return value is hello

Upvotes: -1

user507077
user507077

Reputation:

Sure: print "Result is: ", calcPercentage($a, $b), "\n";

Upvotes: 9

Related Questions