Re: Subroutine return value

Jim Gibson via beginners <[email protected]> Wed, 14 May 2025 17:10:08 -0700
Newsgroups gmane.comp.lang.perl.beginners
Message-ID <[email protected]>
Put this line as the last line executed in your subroutine:=20

	return $sum;

That makes it explicit as to what you want the subroutine to do. Don=E2=80=
=99t 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=E2=80=AFPM, Daryl Lee <[email protected]> =
wrote:
>=20
> In =E2=80=9CLearning Perl=E2=80=9D, Pg. 116, is found this sentence: =
Whatever calculation is last performed in a subroutine is automatically =
also the return value.
>=20
> I have a subroutine that (almost) ends with this loop:
>=20
>     foreach my $line (@lines) {
>         $sum +=3D evaluate($line);
>   }
>=20
> 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:
>=20
>     foreach my $line (@lines) {
>         $sum +=3D evaluate($line);
>   }
> }
>=20
> That was pointless, so I =E2=80=9Cworked around=E2=80=9D the issue by =
adding $sum at the end:
>=20
>     foreach my $line (@lines) {
>         $sum +=3D evaluate($line);
>   }
>     $sum;
> }
>=20
> I think I can remember this in the future, but I=E2=80=99d like to =
understand what=E2=80=99s actually happening.   And I suspect I=E2=80=99m =
offending some veterans by not making Perl-ish use of #_.  Sorry about =
that.
>=20

Jim Gibson
[email protected]




-- 
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/