Perl中的特殊变量

本文介绍了Perl语言中的特殊变量,包括$&,$`, $'在正则表达式匹配中的用途及$_和@_的作用。$&用于保存匹配到的内容,$`和$'分别保存匹配前后的字符串。$_作为默认输入和模式匹配空间,@_则用于存储子程序的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Perl中的特殊变量


1. $&,$`,$'用在模式匹配中


$&用来存放匹配中的值
$`用来存放匹配中之前所有字符
$
'用来存放匹配中之后所有字符

如:
#!/usr/bin/perl-w
if("Hellogoodthere,neigborhello"=~/S(w+),/)
{
print"Thatactuallymatched'$&'.";
print$`."";
print$'." ";
}

执行的结果为:

Thatactuallymatched
'there,'.
Hellogood
neigborhello

----------------------------------------------

另外常用的变量@_
@_是子程序的一个私有变量◆;如果有一个全局变量@_,它将在此子程序调用前存储起来,当子程序调用完成后,其早期的值会被重新赋还给@_◆。这意味着当将参数传递给子程序时不用担心它会影响此程序中其它子程序的@_这个变量的值。嵌套的子程序调用时,@_的值和上述类似。甚至此子程序递归调用时,每一次调用将得到新的@_,因此子程序调用时将得到其自身的参数列表。

◆除非调用的子程序前有&而后面没有括号(或者没有参数),此时@_从此调用者的上下文(context)得到。这通常不是个好主意,但有时很
有用。


2.Perl - $_ and @_


Perl's a great language for special variables - variables that are set up without the programmer having to intervene and providing information ranging from the number of lines read from thecurrent input file ($.)through thecurrent process ID ($$)and theoperating system ($^O). Other special variables effect how certain operations are performed ($| controlling output buffering / flushing, for example), or are fundamental in the operation of certain facilities - no more so than $_ and @_.

Lets clear a misconception.
$_and@_aredifferent variables. In Perl, you can have a list and a scalar of the same name, and they refer to unrelated pieces of memory.

$_ is known as the "default input and pattern matching space".In other words, if you read in from a file handle at the top of awhileloop, or run aforeachloop and don't name a loop variable, $_ is set up for you. Then any regular expression matches,chops (andlcs and many more) without a parameter, and evenprints assume you want to work on $_. Thus:
while ($line = <FH>) {
if ($line =~ /Perl/) {
print FHO $line;
}
print uc $line;
}


Shortens to:
while (<FH>) {
/Perl/ and
print FHO ;
print uc;
}


@_ is the list of incoming parameters to a sub.So if you write a sub, you refer to the first parameter in it as$_[0], the second parameter as$_[1]and so on. And you can refer to$_#as the index number of the last parameter:
sub demo {
print "Called with ",$#_+1," params/n";
print "First param was $_[0]/n";


Note that theEnglishmodule adds in the ability to refer to the special variables by other longer, but easier to remember, names such as @ARG for @_ and $PID for $$. Butuse English;can have a detrimental performance effect if you're matching regular expressions against long incoming strings.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值