代码之家  ›  专栏  ›  技术社区  ›  Stéphan Kochen

Perl等价于Ruby的'reject!'?

  •  5
  • Stéphan Kochen  · 技术社区  · 15 年前

    slice ,但不知道如何在 foreach 上下文。

    在Ruby中,有 reject! :

    foo = [2, 3, 6, 7]
    foo.reject! { |x| x > 3 }
    p foo   # outputs "[2, 3]"
    

    有Perl等价物吗?

    3 回复  |  直到 15 年前
        1
  •  22
  •   knittl    15 年前
    @foo = (2, 3, 6, 7);
    @foo = grep { $_ <= 3 } @foo;
    print @foo; # 23
    
        2
  •  8
  •   pilcrow    15 年前

    grep 通常是你所需要的。

    但是,使用perl是可能的 prototypes 编写一个函数,就像ruby的 Array#reject! :

    • 接受块

    用法是:

    @foo = (2, 3, 6, 7);            # Void context - modify @foo in place
    reject { $_ > 3 } @foo;         # @foo is now (2, 3)
    
    @foo = (2, 3, 6, 7);            # Scalar context - modify @foo in place
    $n = reject { $_ > 3 } @foo;    # @foo is now (2, 3), $n is length of modified @foo
    
    @foo = (2, 3, 6, 7);            # Array context - return a modified copy of @foo
    @cpy = reject { $_ > 3 } @foo;  # @cpy is (2, 3), @foo is (2, 3, 6, 7)
    

    实施:

    sub reject(&\@) {
        my ($block, $ary) = @_;
    
        # Return a copy in an array context
        return grep {! $block->() } @$ary if wantarray;
    
        # Otherwise modify in place.  Similar to, but not
        # quite, how rb_ary_reject_bang() does it.
        my $i = 0;
        for (@$ary) {
                next if $block->();
                ($ary->[$i], $_) = ($_, $ary->[$i]); # swap idiom to avoid copying
                $i++;                                # possibly huge scalar
        }
        $#$ary = $i - 1;  # Shorten the input array
    
        # We differ from Array#reject! in that we return the number of
        # elements in the modified array, rather than an undef value if
        # no rejections were made
        return scalar(@$ary) if defined(wantarray);
    }
    
        3
  •  4
  •   Vinko Vrsalovic    15 年前
    vinko@parrot:/home/vinko# more reject.pl
    my @numbers = (2, 3, 6 ,7);
    print join(",", grep { $_ <= 3 } @numbers)."\n";
    
    vinko@parrot:/home/vinko# perl reject.pl
    2,3