02Home & Garden · Updated
What Does $_ Mean in Perl? The Default Variable
Short answer
$_ is Perl’s default input and topic variable
In Perl, $_ is a special default variable used by many operators and control structures when no other variable is specified. It often holds the current item in a loop or the current line being processed.
What $_ means in Perl
$_ is a predefined Perl variable, usually called the default variable or the topic variable. It provides a value that certain Perl operations use implicitly. That means you can sometimes write a short expression without naming the variable explicitly.
For example, this loop prints each element of an array:
my @colors = qw(red blue green);
for (@colors) {
print "$_\n";
}
Here, $_ refers to the element currently being handled. Perl also lets you omit it in some contexts:
for (@colors) {
print "$_\n";
}
The loop’s body can use $_ directly, and operators such as print can use it as their default input. The variable is not a special spelling of “the last variable” or a placeholder that works everywhere; its role depends on the operator or construct around it.
Why Perl has a default variable
Perl was designed to make common text-processing tasks concise. A program that reads lines, searches for a pattern, or transforms each item often needs to act on one current value at a time. Rather than requiring that value to be named in every expression, Perl provides $_ as a default in many common operations.
This convention is especially visible in short scripts and command-line programs. For instance, chomp removes a record separator from $_ if you do not pass it a variable:
while (<>) {
chomp;
print "You entered: $_\n";
}
The diamond operator <> reads input, commonly from files named on the command line or standard input. In this loop, each read line is assigned to $_; chomp then acts on that value. The behavior is convenient, but it is still useful to know what is being changed.
How implicit use works
Perl documentation often describes an operation as acting on $_ by default. The exact set of operations is not universal: each function or operator has its own rules. A familiar example is a pattern match. The expression below searches the current topic for the word cat:
if (/cat/) {
print "Found cat in: $_\n";
}
Writing the variable explicitly makes the target clear:
if ($text =~ /cat/) {
print "Found cat in: $text\n";
}
Both forms can be appropriate. The implicit form is compact when the surrounding code makes the current value obvious. The explicit form can be easier to follow when a reader has to track several values or when the expression is part of a larger program.
Some functions also use $_ as a default argument. For example, length returns the length of $_ when called without an argument:
$_ = "Perl";
my $count = length; # 4
Do not assume that every function behaves this way. Check the function’s documentation when you are unsure whether an argument can be omitted.
Using $_ in loops and text processing
$_ commonly represents the current value in a for loop, and the current input record in a line-reading loop. That makes it handy for simple transformations:
my @words = qw(Perl makes text work);
for (@words) {
$_ = uc $_;
}
print "@words\n";
In this example, the loop variable aliases each array element, so assigning to $_ changes the corresponding element in @words. This matters: $_ is not always a separate copy of a value. In a loop over an array, modifying the loop variable can modify the array itself.
When that is not intended, use a named loop variable or build a new list. A named variable also documents the value’s purpose:
for my $word (@words) {
print uc($word), "\n";
}
For one-off filtering, Perl’s grep also uses $_ implicitly when its block does not declare another variable:
my @long = grep { length($_) > 4 } @words;
Being explicit inside the block is often a good choice for learners, though grep { length > 4 } @words is a common compact form.
Scope, localization, and common mistakes
Because $_ is implicit, its value can be easy to overlook. Perl constructs often localize the topic variable while they run, meaning their temporary use of $_ is kept separate from an outside value. The details depend on the construct, however, and code that changes $_ in nested loops or callbacks can be harder to reason about.
- Assuming it exists everywhere: An expression only uses
$_implicitly when that operation’s rules say so. Otherwise, a missing or unexpected value may be used. - Forgetting it can change: A loop or function may set or modify the topic. Do not rely on an old value remaining unchanged without checking the surrounding code.
- Confusing it with other dollar variables:
$_is not the same as$1, which holds a captured substring after a successful regular-expression match, or$!, which relates to operating-system errors. - Overusing implicit code: Short syntax can obscure which data is being tested or transformed. Use a named scalar when the meaning is not immediately clear.
For debugging, temporarily making the target explicit often helps. Replacing /pattern/ with $value =~ /pattern/, for example, reveals exactly what the match examines.
When to use $_ or a named variable
Use $_ when it makes a small, familiar operation more readable, such as processing one input line at a time. Prefer a named variable when the code has multiple values, the block is long, or the value’s role needs explanation. This is a readability decision, not a rule that one style is always correct.
Compare these two snippets:
for (@items) {
s/old/new/;
}
for my $item (@items) {
$item =~ s/old/new/;
}
The first is compact: the substitution acts on $_, and in this loop it updates each item. The second names the current value, which may be clearer to someone new to Perl. A team can also adopt a consistent style so that implicit behavior does not surprise readers.
Frequently Asked Questions
How do you pronounce $_ in Perl?
It is commonly read aloud as “dollar underscore.” Some programmers call it the default variable or the topic variable.
What does $_ contain in a Perl foreach loop?
In the form for (@items), $_ represents the current item as the loop progresses. If the loop assigns to it, the corresponding array element can be changed.
Is $_ the same as $ARGV in Perl?
No. $_ is the default topic variable, while $ARGV contains the name of the file currently being read by the diamond operator, when applicable.
Does print use $_ automatically?
Yes, print with no arguments prints the current default topic value. With arguments, it prints the values you provide instead.
Should I avoid using $_?
No. It is a normal and useful part of Perl. Use it when the context is clear, and choose a descriptive named variable when implicit behavior would make the code harder to understand.
Related
- How to Jump-Start a Car With a Screwdriver
- What Is a W-4? How the Employee Tax Form Works
- What Does | Mean in a Regex? The Pipe Explained
Further reading: Perl documentation. Details can change, so check the official page for anything that matters to you. Spotted a mistake? Tell us. How we write an answer.