要注意Perl系统变量值的变化

Wayne posted @ Mon, 10 Dec 2012 10:27:55 +0000 in Experience , 3424 readers

忘了专业点的说法怎么叫了,这里说的系统变量就是指那些 $_, $1, $# 之类的默认设置了的变量。一直以来被告诫要注意的是$_这个变量,一个while循环一个if判断什么的,有可能改变它的值。因为一直注意,倒也没遇到太大障碍。

今天栽在另一个变量上了,$1。语句是这样的:

s/$1/$hash{$1}/gi if /(\w+)/;

执行后发现总是被替换为空字符串。难道是 hash里面没值?我于是改成了:

 s/$1/$hash{$1}/gi if (/(\w+)/ && defined $hash{$1} );

结果还是一样。

进行调试,把相关的值都打出来,发现各个值都取得完全没问题,唯独在 s/xxx/yyyy/gi 这步上出错了。

仔细观察了下substitution的形式特征,我想起来xxx这部分可以是regex的,比如我常用来交换位置的那种做法:

  s/(xxx)(yyyy)/$2$1/g

在这样一句中,很明显 $1,$2的值由前面所决定。回到我出错的这句,估计也是这个原因了。第一个 $1,它取的if中的regex捕捉到的内容,第二个 作为hash的key的$1,它取的是xxx这个位置捕捉的内容。(话说xxx这个位置专业点的叫法是啥来着……)。做个实验验证下:

if (/(\w+)/ && defined $hash{$1} ){

  $replacement = $hash{$1};

  s/$1/$replacement/gi;

}

实验通过,这样果然管用。

 

 

zaeneas said:
Mon, 10 Dec 2012 13:04:36 +0000

有时候我很讨厌Perl这一点

本来觉得不需要再声明变量的,结果发现还是需要很丑陋的声明一个新的变量

pavzi.com said:
Fri, 05 Jan 2024 11:48:33 +0000

Pavzi.com is a startup by passionate webmasters and bloggers who have a passion for providing engaging content that is accurate, interesting, and worthy to read. <a href="https://pavzi.com/">pavzi.com</a> We are more like a web community where you can find different information, resources, and topics on day-to-day incidents or news. We provide you with the finest web content on every topic possible with the help of the editorial and content team.

pavzi.com said:
Fri, 05 Jan 2024 11:49:04 +0000

Pavzi.com is a startup by passionate webmasters and bloggers who have a passion for providing engaging content that is accurate, interesting, and worthy to read. pavzi.com We are more like a web community where you can find different information, resources, and topics on day-to-day incidents or news. We provide you with the finest web content on every topic possible with the help of the editorial and content team.

seo service london said:
Tue, 16 Jan 2024 07:06:07 +0000

I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing


Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter