Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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"; }

Comment on passing return value of a function to print
Download Code
Re: passing return value of a function to print
by farang (Hermit) 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 (Abbot) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1037967]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2014-08-29 01:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (275 votes), past polls