1

I am trying to filter values in an array using grep (in Perl). My goal is to remove array elements where both the "pending" element is INVALID_APNS and the "token" element is empty

This does not work - it deletes everything. The array contains 0 elements after the rep, but should contain 2.

use constant INVALID_APNS => -1;
@active_connections = (
    {
        pending => INVALID_APNS,
        token=>'123'
    },
    {
        pending => INVALID_APNS,
        token=>'123'
    },
    {
        pending => INVALID_APNS,
        token=>''
    },


);
 @active_connections = grep { ($_->{pending} != INVALID_APNS) && ($_->{token} ne '')} @active_connections;
 print scalar @active_connections;

What am I doing wrong?

1 Answer 1

3

If you want to exclude records with $_->{'pending} == INVALID_APNS && $_->{'token'} eq '', you are negating that improperly to get what grep should include. Either of these should do what you want:

! ( $_->{'pending'} == INVALID_APNS && $_->{'token'} eq '' )

or

$_->{'pending'} != INVALID_APNS || $_->{'token'} ne ''

See https://en.wikipedia.org/wiki/De_Morgan%27s_laws

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I seem to have a brain-freeze at the moment. Your solution works - I don't get why mine is wrong. I'll re-look at this tomorrow morning with some strong coffee and once I get it, I'll mark it as resolved. Thank you!
@user1361529 the opposite of "it's big AND it's red" is "it's not big OR it's not red".
Right. I'm an idiot. I can't believe I spent all day on this. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.