Chapter 29. Scoping

Mark Jason Dominus

In the Beginning, some time around 1960, every part of a program had access to all the variables in every other part of the program. This caused a lot of bugs when people forgot where their variables were used, so language designers invented local variables, which were visible in only a small part of the program. That way, programmers who used a variable xcould be sure nobody tampered with the contents of xbehind their back. They could also be sure that by using x, they weren’t tampering with someone else’s variable by mistake.

Every programming language has a philosophy, and these days most of these philosophies have to do with the way the names of variables are managed. Details of which variables are visible to which parts of the program, and what names mean what, and when, are of prime importance. The details vary from somewhat baroque, in languages like Lisp, to extremely baroque, in languages like C++. Unfortunately, Perl is on the rococo end of this scale.

The problem with Perl isn’t that it has no clearly defined system of name management, but rather that it two systems, both working at once. Here’s the Big Secret about Perl variables that most people learn too late: Perl has twocompletely separate, independent sets of variables. One is left over from Perl 4 (the way your vermi-form appendix and midbrain are left over from a previous geologic era), and the other set is new. The two sets of variables are called package variablesand lexical ...

Get Computer Science & Perl Programming 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.