Chinaunix

标题: split的用法请教 [打印本页]

作者: as710054    时间: 2014-01-16 10:31
标题: split的用法请教

为啥 perl的split 不能 直接 split(/pattern/,$str)[4] ,必须(split(/pattern/,$str))[4] ,如果我要取个切片
作者: imshang    时间: 2014-01-16 10:47
加个括号,让split返回list context
作者: yestreenstars    时间: 2014-01-16 13:53
可以少写一层小括号:
  1. (split /pattern/,$str)[4]
复制代码

作者: as710054    时间: 2014-01-16 14:04
回复 3# yestreenstars

为什么必须加外头那个括号?
split 不是返回就是一个列表了么?


   
作者: yestreenstars    时间: 2014-01-16 14:08
回复 4# as710054
我也不知道{:2_169:}

   
作者: uiojkl227    时间: 2014-01-16 14:43
回复 4# as710054


   

得看split操作符所在的环境,现在不是取第五个字段给标量吗?

作者: as710054    时间: 2014-01-16 15:07
回复 6# uiojkl227



my $item = split(/pattern/, $str)[3];
my @items = split(/pattern/, $str)[3];

这两个都是报错的
syntax error at array.pl line 18, near ")["
Execution of array.pl aborted due to compilation errors.

   
作者: imshang    时间: 2014-01-16 16:13
回复 4# as710054


   split的确返回的是列表,但是)和[会优先结合,结果syntax error。个人理解。。。外层括号使得里层列表展开,然后和[]形成切片。
作者: as710054    时间: 2014-01-16 17:07
回复 8# imshang

我也是这么猜测的,那位高人能给详细解释下


   
作者: yybmsrs    时间: 2014-01-16 18:06
[]优先级比较高,先和()结合了
作者: MMMIX    时间: 2014-01-16 20:43
as710054 发表于 2014-01-16 17:07
回复 8# imshang

我也是这么猜测的,那位高人能给详细解释下


Perl 5 并没有十分严格的语法说明,Perl 5 实现的行为就是标准,它说你的写法错了,那就是错了,改过来就是了。除非你想研究它的实现,只是使用的话,许多语法细节真没必要深究。
作者: pitonas    时间: 2014-01-16 21:40
{:2_172:} 我心中一种畅快的感觉呀



回复 10# yybmsrs


   
作者: MMMIX    时间: 2014-01-16 22:30
yybmsrs 发表于 2014-01-16 18:06
[]优先级比较高,先和()结合了

依据何在?
作者: yybmsrs    时间: 2014-01-17 08:58
回复 13# MMMIX


    昨天没找到相关的资料。

    {}和[]结合性高一点,跟C里面int *foo[]这种类似,我一直是这么理解的。
作者: MMMIX    时间: 2014-01-17 09:38
yybmsrs 发表于 2014-01-17 08:58
回复 13# MMMIX

{}和[]结合性高一点,跟C里面int *foo[]这种类似,我一直是这么理解的。


可是 perlop 中还有这么一段:
If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call.

作者: yybmsrs    时间: 2014-01-17 11:32
本帖最后由 yybmsrs 于 2014-01-17 11:35 编辑

回复 15# MMMIX
  1.     Also parsed as terms are the "do {}" and "eval {}" constructs, as well
  2.     as subroutine and method calls, and the anonymous constructors "[]" and
  3.     "{}".
复制代码
嗯,是这样。[]和{}也是当做term来处理。

    <Programming Perl>这本书里面有这么一句话,里面说了must,估计语法就是这么定义的,所以会报语法错误。
  1. A list value may also be subscripted like a normal array. You must put the list in parentheses (real ones) to
  2. avoid ambiguity. Though it's often used to fetch a single value out of a list, it's really a slice of the list, so the
  3. syntax is:

  4. (LIST)[LIST]

  5. Examples:
  6.    # 语法错误
  7.    $modification_time = stat($file)[9];   # 忘记括弧了。
复制代码

作者: MMMIX    时间: 2014-01-17 12:25
回复 16# yybmsrs

    嗯,应该就是 Programming Perl 说的这个原因吧。
作者: uiojkl227    时间: 2014-01-17 13:14
回复 7# as710054


你要取切片,前面一定要是个列表,()产生列表环境。至于优先级倒没有研究过。16#倒是有道理,避免歧义。

   




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2