Re: Subroutine return value

[email protected] (Jim Gibson via beginners)
Newsgroups perl.beginners
Message-ID <[email protected]>
Put this line as the last line executed in your subroutine: 

	return $sum;

That makes it explicit as to what you want the subroutine to do. Don’t depend upon some obscure behavior of Perl to save a few keystrokes. Your program will be better for it.


> On May 14, 2025, at 4:15 PM, Daryl Lee <[email protected]> wrote:
> 
> In “Learning Perl”, Pg. 116, is found this sentence: Whatever calculation is last performed in a subroutine is automatically also the return value.
> 
> I have a subroutine that (almost) ends with this loop:
> 
>     foreach my $line (@lines) {
>         $sum += evaluate($line);
>   }
> 
> What I want to return is the final value of $sum as calculated on the last pass of that loop, so I simply closed the subroutine block right there with }, making it look like this:
> 
>     foreach my $line (@lines) {
>         $sum += evaluate($line);
>   }
> }
> 
> That was pointless, so I “worked around” the issue by adding $sum at the end:
> 
>     foreach my $line (@lines) {
>         $sum += evaluate($line);
>   }
>     $sum;
> }
> 
> I think I can remember this in the future, but I’d like to understand what’s actually happening.   And I suspect I’m offending some veterans by not making Perl-ish use of #_.  Sorry about that.
> 

Jim Gibson
[email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.