Chinaunix首页 | 论坛 | 博客
  • 博客访问: 836248
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-18 15:23:34

  1. perl -le 'my @odd_numbers = grep { $_ % 2 } 1..1000; print @odd_numbers;'
While the grep is running, $_ is aliased to one element of the list after another. You’ve
seen this behavior before, in the foreach loop. It’s generally a bad idea to modify $_
inside the grep expression because this will damage the original data.
  1. perl -le '@files = grep{/*.pl/i} glob "*.*"; print @files;'
  2. my @matching_lines = grep { /\bfred\b/i } ; the same with
  3. my @matching_lines = grep /\bfred\b/i, ;

  1. #!/usr/bin/perl -w
  2. #
  3. use strict;

  4. my @input_numbers = (1, 2, 4, 8, 16, 32, 64);
  5. my @my_num1 = grep $_ > 10, @input_numbers;
  6. my @num1 = grep {!($_ % 4)} @input_numbers;
  7. my @num2 = grep /4$/, @input_numbers;
  8. print "@my_num1, @num2, @num1\n";

  9. my @odd_digit_sum = grep digit_sum_is_odd($_), @input_numbers;
  10. print "@odd_digit_sum\n";#output is 1 16 32

  11. sub digit_sum_is_odd {
  12.     my $input = shift;
  13.     my @digits = split //, $input; # Assume no nondigit characters
  14.     my $sum;
  15.     $sum += $_ for @digits;
  16.     return $sum % 2 ;
  17. }
we can also use below code to complete.
  1. my @r = grep { my $num = $_;
  2.                my $re;
  3.                $re += $_ for split//, $num;
  4.                $re %2;
  5. }(10,30,20,13);#out put 10,30
  1. my %provisions = (
  2.   'The Skipper' => [qw(blue_shirt hat jacket preserver sunscreen)],
  3.   'The Professor' => [qw(sunscreen water_bottle slide_rule radio) ],
  4.   'Gilligan' => [qw(red_shirt hat lucky_socks water_bottle) ],
  5. );

  6. my @need = grep { my @k = @{$provisions{$_}};
  7.                   grep {$_ eq 'water_bottle' } @k;
  8. }keys %provisions;
  9. print "@need";  #out put Gilligan The Professor


阅读(439) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~