general beginner

What is $1 in Perl?

Question

What is $1 in Perl?

Understanding $1 in Perl

In Perl, $1 is a special scalar variable that holds the content of the first capture group from the last successful regular expression match. It is one of several "match variables" ($1, $2, $3, etc.) that represent portions of a string matched within parentheses ().

When you use a regular expression with parentheses to capture parts of a string, Perl saves those captured substrings into these variables:

  • $1 - First capture group
  • $2 - Second capture group
  • $3 - Third capture group
  • ...and so forth

This feature is incredibly useful when you want to extract specific parts of a string.

Key Points About $1

  • Scope: $1 is set after a successful match operator (=~) with capturing parentheses.
  • Perl version: Available since early Perl versions; works consistently in all Perl 5 editions.
  • Lifetime: $1 holds its value until next successful match or is overwritten.
  • Use with caution: Avoid using $1 without an immediately preceding successful regex match; otherwise it retains stale data.
  • Context: It's a scalar and should be used as such.

Example: Extracting a Number from a String


use strict;
use warnings;

my $string = "Order number: 12345";

if ($string =~ /number:\s+(\d+)/) {
    print "Captured number: $1\n";  # Prints: Captured number: 12345
} else {
    print "No match found.\n";
}

# Demonstrating multiple capture groups
my $date = "2024-06-20";

if ($date =~ /(\d{4})-(\d{2})-(\d{2})/) {
    print "Year: $1, Month: $2, Day: $3\n";  # Prints: Year: 2024, Month: 06, Day: 20
}

Explanation of the Code

In the first match, the pattern /number:\s+(\d+)/ searches for the word "number:" followed by one or more whitespace characters and then captures one or more digits (\d+) inside parentheses. These digits are stored in $1, which we then print.

In the second example, the regular expression has three capture groups corresponding to year, month, and day. Each is stored sequentially in $1, $2, and $3.

Common Pitfalls

  • Using $1 without a prior successful regex match—this may print unexpected data or warnings.
  • Assuming $1 stays the same across different matches—it gets overwritten on each successful match.
  • Confusing numeric match variables ($1, $2) with capture variables such as %+ (named captures, Perl 5.10+ feature).

Summary

$1 is a powerful Perl variable that holds the contents of the first capturing group in the most recent successful regular expression match. It makes extracting specific fragments from strings straightforward and intuitive.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Captured number: 12345
Year: 2024, Month: 06, Day: 20
STDERR
(empty)

Was this helpful?

Related Questions