免费注册 查看新帖 |

Chinaunix

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

求教grep的问题 [复制链接]

论坛徽章:
0
发表于 2011-09-08 16:57 |显示全部楼层
  1. #i/usr/bin/perl -w
  2. use strict;
  3. my @numers=(1,2,4,8,11,32,64);
  4. my @sum =grep &odd($_), @numers;
  5. print "@sum \n";

  6. sub odd {
  7.         my $input =shift;
  8.         my @digts = split //, $input;
  9.         my $sum;
  10.         $sum += $_  for @digts;
  11.         return $sum % 2;
  12. }
复制代码
以上代码中 grep那句的$_指的是子函数的返回值么,还是别的什么?

$sum += $_  for @digts; 这句是一个简单的foreach语句么?

代码粘贴字中级perl,以上两个疑问求大牛指教。

论坛徽章:
0
发表于 2011-09-08 17:06 |显示全部楼层
以上代码中 grep那句的$_指的是子函数的返回值么,还是别的什么?

$sum += $_  for @digts; 这句是一个简单的foreach语句么?


1. 第一个$_ 是指 后面要遍历的数组的每个值的副本别名。
2. 是一个简单的 foreach 遍历语句变形。

相当于
  1. foreach (@digts) {
  2.     $sum += $_;
  3. }
复制代码

论坛徽章:
0
发表于 2011-09-08 17:08 |显示全部楼层
大牛木有,小牛指点你:
  1. perldoc -f grep
  2. Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element)
  3.                and returns the list value consisting of those elements for which the expression evaluated
  4.                to true.  In scalar context, returns the number of times the expression was true.
复制代码
  1. foreach(@digts){$sum += $_ }
复制代码

论坛徽章:
0
发表于 2011-09-08 17:10 |显示全部楼层
回复 2# Perlvim


   
1. 第一个$_ 是指 后面要遍历的数组的每个值的副本别名。

这个依然不懂,什么是每个值的副本别名?

论坛徽章:
0
发表于 2011-09-08 17:14 |显示全部楼层
  1. foreach my $element (@array) {
  2.     # do something....
  3.     print $element;
  4. }

  5. foreach (@array) {
  6.     # do something...
  7.     print $_;
  8. }
复制代码
第一段代码中的 $element 相当于第二段代码中的 $_

就是默认的 $element.

论坛徽章:
0
发表于 2011-09-08 17:19 |显示全部楼层
回复 5# Perlvim


    这两段代码明白,看来我还是没有搞懂grep
    谢了。

论坛徽章:
0
发表于 2011-09-08 18:52 |显示全部楼层
不懂
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP