作者gugod (啊)
看板Perl
标题Re: [问题] perl grep()与$_
时间Sat Jul 24 01:56:25 2010
※ 引述《nuzleaf (送高中参考书)》之铭言:
: 各位大大您好 我是一个perl新手 有很多问题想请教
: 不过都是为了de一个bug来的 谢谢!
: a. grep(A,B) A的部分是不是一定要放regular expression?
: 假设我 $str= "perl_newbie"; @result = grep($str,@array);
: 这样好像会回传所有array的值 而grep(/$str/,@array)才能找到
: array里相对应的值 不知道我有没有搞错 那前者为什麽没有compile error?
grep 的第一个参数也可以是 block (code ref), 不过这与您的问题没有直接关系。
事实上这是个很有意思的问题。在此引用 'perldoc -f grep' 前两段:
grep BLOCK LIST
grep EXPR,LIST
This is similar in spirit to, but not the same as, grep(1) and
its relatives. In particular, it is not limited to using
regular expressions.
Evaluates the BLOCK or EXPR for each element of LIST (locally
setting $_ to each element) and returns the list value
consisting of those elements for which the expression evaluated
to true. In scalar context, returns the number of times the
expression was true.
基本上写 grep($str, @array) 与 grep(/re/, @array) 对应到的都是第二
种语法。而这种语法的解读方式是:
将每个 @array 里的值一一设成 $_ 後,去取 EXPR 的值
如果 EXPR 是 /re/ 的话,发生的事就像是
$_ = $array[0];
if (/re/) { push @result, $_ }
$_ = $array[1];
if (/re/) { push @result, $_ }
# ... 如此这般一直重复下去
如果 EXPR 是 $str 的话,则是
$_ = $array[0];
if ($str) { push @result, $_ }
$_ = $array[1];
if ($str) { push @result, $_ }
# ... 如此这般
也就是说,if ($str) 的部份永远会成立,@result 的内容自然也就是通吃了。
至於,为何这没有 compiler error ? 那是因为一个「字串」也是一个有效的
EXPR (expression / 算式)。其实 grep 也可以这样用:
# 找出 @array 中所有正好是 "foo" 的值
@result = grep $_ eq "foo", @array;
# 找出 5 < $_ < 10 的值
@result = grep 5 < $_ && $_ < 10, @array;
这部份应该是有点旧的语法,而在 Perl5 中一直支援旧的语法。因此,
单单一个字串并没有 compile error。不过我个人认为起码可以有个 warning。
读起来比较不讨人厌的写法,现在是用 block:
@result = grep { 5 < $_ && $_ < 10 } @array;
猛一看好像没太大差别?不过多一组大括号确实有助於阅读。
: b. regular expression 里 我若打 $str = "/aaa/bbb{2}/ccc[0]/";
: 然後在某处用到 =~m/$str/ 到底意义是甚麽?
: 是 m//aaa/bbb{2}/ccc[0]//
: 还是 m/aaa/bbb\{2\}/ccc\[0\]/
: 可不可以帮我解答一下? 尤其是最前面和最後的/ /需要跳脱字元吗?
建议您在与到 $str 中有 "/" 时,把 m// 换个括号,像 m{} 就完全没有
解读上的困扰。
$x =~ m/\/aaa\/bbb{2}\/ccc[0]\//;
这等价於
$x =~ m{/aaa/bbb{2}/ccc[0]/};
另一方面,以下後三行也是等价的:
$str = "/aaa/bbb{2}/ccc[0]/";
$x =~ m/$str/;
$x =~ m/\/aaa\/bbb\{2\}\/ccc\[0\]\//;
$x =~ m{/aaa/bbb\{2\}/ccc\[0\]/};
希望这例能帮助您理解到在 regular expression 中内插字串的状态。
: c. 请问关於$_,有没有一个比较统一的规则可以解释
: 我目前只知道 while(<INFILE>) {
: print $_;
: }
: 或是 print $_ foreach(@array);
: 但常常写错 不知道为什麽 请问$_的scope在哪里
: 有哪些function或操作 会implicit的用到$_??
: 感谢大大 ~~
$_ 是全域变数。`perlfoc perlfunc` 中列出的内建函式大部份都
会去用 $_ 。
--
Scheme teaches us that :
"An integer is a rational is a real is a complex number is a number."
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.32.222.155
1F:推 cutecpu:推! 07/24 08:07
2F:推 herculus6502:颈推! 07/24 16:26
3F:推 jakechou:膑숡!看不太懂但是我会好好研究 07/30 11:59
4F:推 nuzleaf:谢谢您 太详细了 07/30 12:04