perlperlperl has asked for the wisdom of the Perl Monks concerning the following question:

Can you pass the return value of a sub directly to the print function? The code below does not print the return value of func which is "123". In fact calling print that way seems to mess up my console; nothing further prints properly. So, can you pass a return value directly to print? If not what is the best way to do it? This is possible in C++ so I had a natural inclination to use it.
print func; sub func { return "123"; }

Replies are listed 'Best First'.
Re: passing return value of a function to print
by farang (Chaplain) on Jun 10, 2013 at 00:20 UTC

    Call the function properly and it works. Note parentheses.

    use strict; use warnings; print func(); sub func { return "123"; }
    Also I have added use strict; and use warnings; which is highly recommended and would have given you valuable feedback as to what the problem was.

    Unquoted string "func" may clash with future reserved word ... print() on unopened filehandle func ...
Re: passing return value of a function to print
by NetWallah (Canon) on Jun 10, 2013 at 00:41 UTC
    As an alternative to farang's (++) method: Declare the sub first, then you don't need the parens:
    perl -e ' sub f {"123\n"}; print f' # prints '123'
    You could also pre-declare a stub, use it, then add the code for the sub:
    perl -e 'sub f;print f; sub f {"123\n"}'

                 "The trouble with the Internet is that it's replacing masturbation as a leisure activity."
            -- Patrick Murray