- 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.
- perl -le '@files = grep{/*.pl/i} glob "*.*"; print @files;'
- my @matching_lines = grep { /\bfred\b/i } ; the same with
- my @matching_lines = grep /\bfred\b/i, ;
- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
my @input_numbers = (1, 2, 4, 8, 16, 32, 64);
-
my @my_num1 = grep $_ > 10, @input_numbers;
-
my @num1 = grep {!($_ % 4)} @input_numbers;
-
my @num2 = grep /4$/, @input_numbers;
-
print "@my_num1, @num2, @num1\n";
-
-
my @odd_digit_sum = grep digit_sum_is_odd($_), @input_numbers;
-
print "@odd_digit_sum\n";#output is 1 16 32
-
-
sub digit_sum_is_odd {
-
my $input = shift;
-
my @digits = split //, $input; # Assume no nondigit characters
-
my $sum;
-
$sum += $_ for @digits;
-
return $sum % 2 ;
-
}
we can also use below code to complete.
- my @r = grep { my $num = $_;
-
my $re;
-
$re += $_ for split//, $num;
-
$re %2;
-
}(10,30,20,13);#out put 10,30
- my %provisions = (
-
'The Skipper' => [qw(blue_shirt hat jacket preserver sunscreen)],
-
'The Professor' => [qw(sunscreen water_bottle slide_rule radio) ],
-
'Gilligan' => [qw(red_shirt hat lucky_socks water_bottle) ],
-
);
-
-
my @need = grep { my @k = @{$provisions{$_}};
-
grep {$_ eq 'water_bottle' } @k;
-
}keys %provisions;
-
print "@need"; #out put Gilligan The Professor
阅读(481) | 评论(0) | 转发(0) |