control-flow intermediate

How to use the $_ default variable in loops in Perl?

Question

How to use the $_ default variable in loops in Perl?

Using the $_ Default Variable in Loops in Perl

In Perl, the $_ variable is the so-called "default input and pattern-searching space," used implicitly in many operations, especially loops. It’s a core part of Perl’s philosophy of TMTOWTDI ("There’s More Than One Way To Do It"), letting you write concise and expressive code by omitting explicit variable names when appropriate.

When iterating with loops, $_ is automatically set to the current element of an array, the current line from input, or the current item in a block—depending on the loop construct. Understanding this lets you write clean loops without needing to declare or reference explicit loop variables.

How $_ Works in Different Loop Constructs

  • foreach and for: When you omit the iterator variable, $_ is implicitly used to hold each element.
  • while loops processing input from <> or other sources often assign data to $_ by default.
  • Many built-in functions and regex operations use $_ implicitly if no operand is provided.

This lets you write code like this:

for (@array) {
    print "Value is: $_\n";
}

Here, @array is iterated, and $_ automatically receives each element in turn without explicit assignment. You then use $_ inside the loop body.

Example: Using $_ in a Loop

#!/usr/bin/perl
use strict;
use warnings;

my @words = qw(perl python ruby javascript);

# Iterate over @words, implicitly using $_ for each element
for (@words) {
    # $_ holds the current element
    # Transform and print the word in uppercase
    print uc($_), "\n";
}

# Another example: while reading from STDIN line by line
print "Enter lines (Ctrl+D to end):\n";
while (<>) {
    chomp;           # chomp uses $_ implicitly
    next if $_ =~ /^#/;  # Skip comment lines starting with #
    print "You entered: $_\n";  # Use $_ directly
}

This script demonstrates two common patterns:

  • for (@words) implicitly sets $_ to each word, letting you use $_ without extra variables.
  • while (<>) reads lines from STDIN into $_ by default, which can be processed directly.

Perl Concepts Highlighted

  • Sigils: $_ always has a scalar sigil because it contains a single scalar value.
  • Context: In a for (@array), $_ is set to each element in scalar context, meaning one scalar at a time.
  • Implicit Usage: Many Perl built-ins (e.g., chomp, regex match =~, and print) operate on $_ when no argument is given.
  • TMTOWTDI: You can explicitly use a named variable (for my $word (@words)), but for (@words) with $_ is succinct and idiomatic.

Common Pitfalls

  • Modifying $_ inside the loop (e.g., $_ = ...) affects the loop variable itself, which sometimes is not intended.
  • Using $_ outside its intended lexical scope can cause unexpected behavior, so avoid relying too heavily on it in large or complex code.
  • With nested loops both using $_, inner loops overwrite the outer $_, so be cautious.

Summary

The $_ variable is Perl’s handy default scalar that simplifies loops and other constructs by reducing boilerplate. In loops like for (@list) or while (<>), Perl automatically assigns the current item to $_, so you can focus on processing the data without explicitly naming loop variables. This leads to cleaner, more idiomatic Perl code.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 8ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions