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

I know this is a simple question, but I can't figure it out. If I want to print the return value from a function without first assigning it to a scalar, how do I do that? If I just use print "$object->function_call()" then information about the reference is printed out. What I want is to print whatever function_call returns.

2006-04-01 Retitled by Corion, as per Monastery guidelines
Original title: 'Simple Perl Question'

  • Comment on Simple Perl Question: Printing the Return Value of a Function

Replies are listed 'Best First'.
Re: Simple Perl Question: Printing the Return Value of a Function
by xdg (Monsignor) on Mar 31, 2006 at 23:57 UTC

    As is typical for Perl, there's more than one way to do it.

    You can use it in the list of arguments to print:

    print "Result: ", $object->function_call(), "\n";

    You can concatenate it as a string into a single argument to print:

    print "Result: " . $object->function_call() . "\n";

    There is also a "trick" you can use to evaluate a function in the middle of a quoted section of text:

    print "Result: @{ [ $object->function_call() ] }\n";

    This causes Perl to create an anonymous array (the square brackets) with the results of the function and immediately dereference it to an array ( the @{ } part ). Within double-quotes, that array is joined with spaces and inserted into the string.

    That extra formatting is often a nice touch versus the other options above, though some people think it's clearer to do something like this:

    print "Result: " . join(" ", $object->function_call() ) . "\n";

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Simple Perl Question: Printing the Return Value of a Function
by zentara (Cardinal) on Mar 31, 2006 at 23:28 UTC
    There is no one answer, as the output can be anything from scalar reference to a hash reference. But a good way to start the "detective work" is
    use Data::Dumper; my $return = $object->function_call(); print "$return\n"; # will tell you what the ref type is print Dumper( [ \$return ] ), "\n";
    Now there can be some glitches. If the function call returns an array, and you try to catch it in $return, you may only get the first array element. But that is what the perldocs are for. They tell you what the methods return.

    I'm not really a human, but I play one on earth. flash japh
Re: Simple Perl Question: Printing the Return Value of a Function
by runrig (Abbot) on Mar 31, 2006 at 23:38 UTC
    Do not put the method call in quotes. I think what you want is:
    print $object->function_call(), "\n";