Implicit Ideas: The Default Scalar Variable

Perl code can seem dense at first, but it’s full of linguistic shortcuts. These allow experienced programmers to glance at code and understand its important implications. Context is one shortcut. Another is default variables—the programming equivalent of pronouns.

The default scalar variable

The default scalar variable (or topic variable), $_, is most notable in its absence: many of Perl’s built-in operations work on the contents of $_ in the absence of an explicit variable. We can still type $_ if it makes our code clearer to us, but it’s often unnecessary.

Many of Perl’s scalar operators (including chr, ord, lc, length, reverse, and uc) work on the default scalar variable if we don’t provide an alternative. For example, the chomp built-in removes any trailing newline sequence (technically the contents of $/; see perldoc -f chomp) from its operand:

Get hands-on with 1200+ tech skills courses.