Returning Values from Subroutines

Calling a subroutine by itself on one line is one way of splitting the execution of a script to a subroutine, but more useful is a subroutine that returns a value. With return values, you can nest subroutine calls inside expressions, use them as arguments to other subroutines, or as parts of other Perl statements (depending on whether the return value is appropriate, of course).

By default, the return value of a Perl script is the last thing that was evaluated in the block that defines the subroutine. So, for example, here's a short Perl script to read in two numbers and add them together:

 $sum = &sumnums(); print "Result: $sum\n"; sub sumnums { print 'Enter a number: '; chomp($num1 = <STDIN>); print 'Enter ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.