Subroutines
Subroutines are functions that accept arguments and can return the result. Usually subroutines are used to eliminate duplication in code, make it clearer and more understandable.
Let's say you want to convert 5 miles to kilometers. You would write something like this:
# Convert 5 miles to kilometers say 5 * 1.609344
But what if you wanted to convert 10 miles to kilometers or any other arbitrary number? In this case we create a subroutine that we can use lately.
sub miles_to_kilometers { my ($miles) = @_; return $miles * 1.609344; } say miles_to_kilometers(5); say miles_to_kilometers(10); say miles_to_kilometers(42);
The subroutine needs a bit of explanation. my ($miles) = @_
is called arguments unpacking
. In Perl arguments when passed to the subroutine go the default array @_
(this is also a special Per variable, just like $_
). You can use all the array-specific functions on the default array too of course.
Exercise
Write and use a subroutine that converts kilometers to miles and print 4, 6, 9 kilometers converted to miles (one kilometer is 0.621371192 miles).
sub kilometers_to_miles { my ... return ... } say kilometers_to_miles(4); say kilometers_to_miles(6); say kilometers_to_miles(9);