Skip to content

Perl 特殊变量

Perl 有许多预定义的特殊变量(special variables),它们具有特定的含义和行为。这些变量通常使用标点符号(例如 $_、$!、@_),或者在使用 use English; pragma 后拥有更长、更具描述性的英文名称。

理解这些变量是编写地道(idiomatic)且有效的 Perl 代码的关键。有些是只读的,而有些可以修改以改变 Perl 的行为。

也许最著名的特殊变量是 $_。它充当许多函数和操作的默认参数或目标,如果在调用时没有显式提供。

#!/usr/bin/env perl
use strict;
use warnings;
my @words = ('hickory', 'dickory', 'doc');
# Example 1: foreach loop
foreach my $word (@words) { # $word is explicitly used
print "Word: $word\n";
}
print "---\n";
# foreach loop implicitly uses $_
foreach (@words) {
print "Implicitly: $_\n";
chomp; # chomp acts on $_ by default
s/i/I/g; # substitution acts on $_ by default
print "Modified: $_\n";
}
print "---\n";
# Example 2: Reading from STDIN
# print "Enter some text: ";
# while (<STDIN>) { # <STDIN> reads a line into $_
# print "You entered: $_" if defined $_;
# }
# (Commented out for non-interactive execution)
$_ = "Test string for functions\n";
print; # prints $_ by default
print "Length of '$_': ", length, "\n"; # length operates on $_ by default

$_ 作为默认值的常见用途包括:

  • 在 foreach 循环中,如果没有指定显式变量,则作为迭代器变量。
  • 许多一元函数(unary functions)的参数(例如 print、chomp、chop、lc、uc、length、defined,文件测试操作符如 -f)。
  • 当未使用 =~ 操作符时,模式匹配(m//)、替换(s///)和转写(tr///)的目标。
  • 行输入操作符(例如 <FILEHANDLE>)存储行的变量,尤其是在 while (<FH>) 这样的 while 循环条件中。
  • grep 和 map 中的隐式迭代器变量。

为了提高可读性,你可以使用 English pragma,它为许多晦涩的特殊变量提供了更长、更具描述性的别名。例如,$! 变为 $OS_ERROR。

#!/usr/bin/env perl
use strict;
use warnings;
use English qw( -no_match_vars ); # -no_match_vars avoids performance hit of $`, $&, $'
open my $fh, '<', 'non_existent_file.txt'
or die "Cannot open file: $OS_ERROR\n"; # $OS_ERROR is alias for $!
# $PID is alias for $$
print "Current Process ID: $PID\n";

特殊变量大致可分为:

  • 全局标量特殊变量 (Global Scalar Special Variables)
  • 全局数组特殊变量 (Global Array Special Variables)
  • 全局哈希特殊变量 (Global Hash Special Variables)
  • 全局特殊文件句柄 (Global Special Filehandles)
  • 全局特殊常量 (Global Special Constants)
  • 正则表达式特殊变量 (Regular Expression Special Variables)
  • 特定文件句柄的特殊变量 (通常与格式 Format 相关) (Filehandle-Specific Special Variables)

这些是具有全局作用域和特殊含义的标量变量。

这些变量在正则表达式成功匹配后设置。

注意:使用 $, $&, 或 $' 会降低程序中所有正则表达式匹配的速度。现代 Perl 通常鼓励使用 @- 和 @+ (匹配开始/结束位置) 或命名捕获 (%+, %-) 配合 /p 标记或 use re 'strict'; 来获得更好的性能和清晰度。

特定文件句柄的特殊变量(通常用于格式 Format)

Section titled “特定文件句柄的特殊变量(通常用于格式 Format)”

这些变量通常影响当前选定的输出文件句柄(参阅 select())。许多与 Perl 的 format 特性有关,该特性在现代 Perl 中很少使用。

$[:这个变量用于设置数组的起始索引,自 Perl 5.30 版本起已被移除。数组索引始终从 0 开始。

$#:虽然 $#array_name 仍然给出 @array_name 的最后一个索引,但单独使用 $# 设置数字默认输出格式的功能已弃用,并在现代 Perl 中无效。