in reply to performing operation on elements not in list?

Like this perhaps

$ perl -le ' > %h = ( one => 1, two => 1, three => 1 ); > $inv = do{ local $" = q{|}; qr{^@{ [ qw{ two three } ] }$} }; > map $h{ $_ } = 0, grep ! /$inv/, keys %h; > print qq{$_ - $h{ $_ }} for keys %h;' three - 1 one - 0 two - 1 $

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: performing operation on elements not in list?
by ikegami (Patriarch) on Jan 09, 2009 at 21:46 UTC
    Two errors.
    • You end up with qr/^two|three$/ which matches "twoo".
    • You don't convert the keys to regexp

    If the list of keys to keep is static, you want

    my $inv = qr/two|three/;

    If the list of keys to keep is dynamic, you want

    my $inv = do{ local $" = q{|}; qr{@{[ map quotemeta, @keep ]}} };

    or the much simpler

    my ($inv) = map qr/$_/, join '|', map quotemeta, @keep;

    In all cases, use /^$inv\z/ in the grep.

      Good catch regarding the anchors and alternation. The OP says "given the same ... list" so the keys not to change are invariable. So I should have said.

      $inv = do{ local $" = q{|}; qr{^(?:@{ [ qw{ two three } ] })$} };

      I'm not sure what you mean when you say I don't convert the keys to regexp.

      Cheers,

      JohnGG

        So I should have said.

        No, that's insanely complex for a static pattern.

        Also, I prefer to put the anchors in the parent regexp. It makes more sense conceptually, the code pattern work in more situations, and you don't have to add (?:) since qr// adds one for you.

        I'm not sure what you mean when you say I don't convert the keys to regexp.

        Injection bug. See the addition of quotemeta in the last two snippets.

        So I should have said.

        No, that's insanely complex for a static pattern.

        Also, I prefer to put the anchors in the parent regexp. It makes more sense conceptually, the code pattern work in more situations, and you don't have to add (?:) since qr// adds one for you.

        I'm not sure what you mean when you say I don't convert the keys to regexp.

        Injection bug. See the addition of quotemeta in the last two snippets.