前一段时间有人问我的"奇怪"的问题,我将如何实现map用grep.今天我试着去做,这就是出来的.我是否从Perl中挤出了所有东西,还是有其他更聪明的黑客?
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
sub my_map(&@) {
grep { $_= $_[0]->($_) } @_[1..$#_];
}
my @arr = (1,2,3,4);
#list context
say (my_map sub {$_+1}, @arr);
#scalar context
say "".my_map {$_+1} @arr;
say "the array from outside: @arr";
say "builtin map:", (map {$_+1} @arr);
Run Code Online (Sandbox Code Playgroud)
ike*_*ami 11
你确定他们没有问如何实现grep用map?这有时真的很有用.
grep { STMTs; EXPR } LIST
Run Code Online (Sandbox Code Playgroud)
可写成
map { STMTs; EXPR ? $_ : () } LIST
Run Code Online (Sandbox Code Playgroud)
(有一点不同:grep返回左值,而map不是.)
知道这一点,人们可以紧凑
map { $_ => 1 } grep { defined } @list
Run Code Online (Sandbox Code Playgroud)
至
map { defined ? $_ => 1 : () } @list
Run Code Online (Sandbox Code Playgroud)
(我更喜欢"未压缩"版本,但"压缩"版本可能更快一些.)
至于实现map使用grep,你可以利用grep循环和别名属性.
map { STMTs; EXPR } LIST
Run Code Online (Sandbox Code Playgroud)
可写成
my @rv;
grep { STMTs; push @rv, EXPR } LIST;
@rv
Run Code Online (Sandbox Code Playgroud)