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

In following code output thrown is hello1. Why does it print 1 alongwith the output hello???

#! usr/bin/perl -w sub foo { print "hello"; #return "Neha"; } print foo; print "\n";
  • Comment on print subroutine name calls subroutine but with appended 1 number to the output
  • Download Code

Replies are listed 'Best First'.
Re: print subroutine name calls subroutine but with appended 1 number to the output
by roboticus (Chancellor) on May 01, 2012 at 18:25 UTC

    You're printing "hello" on line 5. But the foo subroutine returns the result from print to the calling line. The problem is that you're printing that result, too. Print returns a true value when successful, evidentally 1 in this case.

    Change line 5 to:

    return "hello";

    and you'll get the results you were looking for.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: print subroutine name calls subroutine but with appended 1 number to the output
by jwkrahn (Abbot) on May 01, 2012 at 18:27 UTC

    What you are effectively doing is:

    print print "hello";

    The first print prints the string "hello" and the second print prints the return value of the first print which is 1.

Re: print subroutine name calls subroutine but with appended 1 number to the output
by 2teez (Vicar) on May 01, 2012 at 19:44 UTC

    As stated by others the 1 shows that the subroutine does its job and return even when return was not stated explicitly, for all it worth, it should also be noted that subroutine should also be called with parentheses like this:

    foo();
    even when no parameter is been passed.
    Reason ( Imagine this: calling the subroutine before it's decleared):
    foo; ## Oops sub foo { print "hello"; } print "\n";
    but with
    foo(); # it works

      Thank you everyone!