Using Local Variables in Subroutines

Structuring a Perl script to use subroutines that refer to the same global variables as the code outside the subroutines is essentially an exercise in code formatting. The subroutines in this case don't give you much intrinsic value in terms of efficiency or effective script design. Subroutines are much better designed and used as self-contained units that have their own variables and that deal only with data passed to that subroutine through arguments and passed back through return values. This makes them easier to manage, easier to reuse, and easier to debug. We'll work towards that goal as this lesson progresses, but we'll start here with a discussion of local variables.

The vast majority of the variables ...

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.