in reply to Re: Print Vs Return In a Subroutine
in thread Print Vs Return In a Subroutine

print and return do completely different things. By default the return value of a perl subrouting is the return value of last evaluated statement. The return value of the print statement is "1" (if it succeded, which is likely always) and the return value of return statement ist the variable you passed to it (or undef if nothing has been passed).

Take a look at this code:

#perl my $variable = 234; sub ax { print $variable; print "\n"; } sub bx { $variable; } my $return_val_a = ax(); print "a - [$return_val_a]\n"; my $return_val_b = bx(); print "b - [$return_val_b]\n";
This will produce this output:
234 a - [1] b - [234]
where you can see the difference a() returns one and b() returns the valus of the variable.

Replies are listed 'Best First'.
Re^3: Print Vs Return In a Subroutine
by heatblazer (Scribe) on Mar 30, 2012 at 18:06 UTC

    No offense here but in that example I don`t see the point in return/print issue the author of the node asked. I am new to Perl, but as far as I got it the return statement of ax() function you defined is returning 1 because of the successful printing, while bx() just returns a variable content. If print is a function then calling it from another function is the same as calling sprintf... which one of them is better, that I don`t know. Since it`s more than 1 way to do it, I think the owner of this node must choose for him/herself.

      This is exactly the point the question is not clear to me. The question sound a bit like "I'm singing" and "I'm dancing" what's faster? The difference between return value and print out to the screen is less in terms of speed but much more in terms of what are going to do? If you are happy with printing the result of the sub to the screen - go on there is nothing wrong with it and there is also no need to return the result to a caller and print it there. But if you want to collect the results of the calculation and do furher processing maybe an average of multiple runs or save it to the database there is the only way to pass a value back to the caller and printing to a screen is completely useless.