Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

passing return value of a function to print

by perlperlperl (Novice)
on Jun 10, 2013 at 00:00 UTC ( #1037967=perlquestion: print w/replies, xml ) Need Help??
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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1037967]
Approved by GrandFather
Jar. Jar!...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2018-07-22 20:52 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (455 votes). Check out past polls.