免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2009 | 回复: 5

奇怪的perl的变量定义位置问题 [复制链接]

论坛徽章:
0
发表于 2009-10-25 08:11 |显示全部楼层
有一个程序如下(文件名为test.pl):

  1. #!/usr/bin/perl
  2. my ($line, $fname, $fh);
  3. local $/;

  4. foreach $fname (@ARGV)
  5. {
  6.    my $rfcnum;
  7.    open $fh, $fname;
  8.    $line = <$fh>;
  9.    $line=~s#RFC\s?(\d{1,4})(?{$rfcnum=substr(100000+$1,-4);})#<a href="/rfc/rfc$rfcnum.htm" target="_top">$&</a>#g;
  10.    print $line, "\n";
  11.    close $fh;
  12. }
复制代码


有两个文件t1.txt和t2.txt,内容相同,都是如下所示:
RFC1234 RFC 2345

然后执行:
ls t?.txt|xargs ./test.pl
结果如下:

<a href="/rfc/rfc1234.htm" target="_top">RFC1234</a>  <a href="/rfc/rfc2345.htm" target="_top">RFC 2345</a>

<a href="/rfc/rfc.htm" target="_top">RFC1234</a>  <a href="/rfc/rfc.htm" target="_top">RFC 2345</a>
请大家看一下,为什么第二行与第一行不一样呢?

如果把 my $rfcnum移到foreach 外面,两行就一样了。

有谁知道为什么?

[ 本帖最后由 billypeng 于 2009-10-25 13:24 编辑 ]

论坛徽章:
0
发表于 2009-10-25 13:21 |显示全部楼层
看其他问题的回复,两位版主都已光临过。

可怜我的问题,还没有一个人回复。

难道这是传说中perl的bug?

[ 本帖最后由 billypeng 于 2009-10-25 13:25 编辑 ]

论坛徽章:
0
发表于 2009-10-28 12:49 |显示全部楼层
perldoc perlre看了一下
(?{})这是一个experimental的feature,所以即使有bug也是可以理解的
然后里面有两段话值得注意
Due to an unfortunate implementation issue, the Perl code contained in these blocks is treated as a
                 compile time closure that can have seemingly bizarre consequences when used with lexically scoped
                 variables inside of subroutines or loops.  There are various workarounds for this, including simply
                 using global variables instead.  If you are using this construct and strange results occur then
                 check for the use of lexically scoped variables.

文档了里面也说了这个玩意和lexical variable碰到一起有点问题

然后
Because Perl's regex engine is currently not re-entrant, interpolated code may not invoke the regex
                 engine either directly with "m//" or "s///"), or indirectly with functions such as "split".

这也就是说你不能在嵌入式的代码里面使用regex,不管是间接的还是直接的,substr属于regex的间接形式


结论:这个有空的话可以去反映一下

评分

参与人数 1可用积分 +2 收起 理由
兰花仙子 + 2 我很赞同

查看全部评分

论坛徽章:
0
发表于 2009-10-28 14:36 |显示全部楼层

回复 #3 churchmice 的帖子

churchmice,赞一个

论坛徽章:
0
发表于 2009-10-28 15:22 |显示全部楼层
原帖由 兰花仙子 于 2009-10-28 14:36 发表
churchmice,赞一个

论坛徽章:
0
发表于 2009-10-28 16:13 |显示全部楼层

回复 #3 churchmice 的帖子

谢谢呀,我没有想到是正则表达式方面的问题,以后知道避免了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP