Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Doubt in functions

by monsoon (Pilgrim)
on Jul 06, 2012 at 00:18 UTC ( #980189=note: print w/ replies, xml ) Need Help??


in reply to Doubt in functions

Quote from http://perldoc.perl.org/perlsub.html

"If no return is found and if the last statement is an expression, its value is returned."


Comment on Re: Doubt in functions
Re^2: Doubt in functions
by ww (Bishop) on Jul 06, 2012 at 00:55 UTC

    update: inadvertently answered monsoon instead of OP. My mistake. I read the doc quotation as the element about which OP had "doubt."</update>

    Perhaps the example will help:

    #!/usr/bin/perl use 5.014; # 980189 sub add_with_return { my $in_in_sub; my $in2_in_sub; $in_in_sub = $_[0]; # For utter clarity; no doubts; # @_ is the array passed to the s +ub $in2_in_sub = $_[1]; # $_[0] & $_[1] are the first two + elements of @_ my $out_in_sub = $in_in_sub + $in2_in_sub; return $out_in_sub; } sub concat_w_NO_return { my ($in_in_sub, $in2_in_sub); $in_in_sub = $_[0]; # For utter clarity; no doubts; # but MANY simpler & BETTER ways +to do this my $in2_in_sub = $_[1]; my $concat = "$in_in_sub" . "$in2_in_sub"; # Last statement, no r +eturn; so the } # computed value of $c +oncat gets returned my $in = 1; my $in2 = 2; my $str1 = "foo"; my $str2 = "bar"; my $sum = add_with_return($in, $in2); say "\t \$sum: $sum"; my $output = concat_w_NO_return($str1, $str2); say "\t \$output: $output";

    Output:

    $sum: 3 $output: foobar

    P.S.: perldoc -f return puts the explanation this way:

    (In the absence of an explicit "return", a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2015-07-07 01:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (86 votes), past polls