in reply to Re: Removing numerous entries from an array
in thread Removing numerous entries from an array

Challenge accepted :)

First, I went to read perlvar to refresh my memory on what the $" special variable is (list separator), so I was able to weasel the code down to this:

my @out = grep { -1 == index " @{find} ", " ${_} " } @a;

Already knowing that grep works 'backwards', I then followed that up with a peruse of perldoc -f index, and found out that the order of args are STRING, SUBSTR and POSITION. In this case, we're not using POSITION, as $_ is the value of the current array element, and is the SUBSTR to index().

So after I realized that "q@{find}q" was simply flattening the @find array into a string of its values separated by a different separator (which I changed back to the default whitespace), I was able to simplify a bit further:

my @out = grep { -1 == index " @find ", $_} @a;

Because although there are spaces around each element in the string-ified list, the whitespace regarding the SUBSTR is irrelevant, because index() is simply checking whether SUBSTR is in STRING, not checking for an exact match.

Because if this, I figured I could chop off two more chars:

my @out = grep { -1 == index "@find", $_} @a;

Lastly, in the previously mentioned perldoc -f index, it states that if the SUBSTR is not found in STRING, it'll return -1. In the last operation of the grep, you check to see if the return from index() is equal to -1, and if true (ie., the substr isn't found in the string-ified @find array), you push it onto the @out array, because grep does so when the block returns a true value. So you convert the expression to a true value after you've found that the original array doesn't match anything in the @find array.

Am I close? ;)

-stevieb

Replies are listed 'Best First'.
Re^3: Removing numerous entries from an array
by Anonymous Monk on Sep 15, 2015 at 00:44 UTC
    Try this:
    my @a = (1, 2, 3, 4, 3, 5, 3, 34); my @find = (4, 3, 53); my @out = grep { -1 == index "@find", $_ } @a;
    :)

      I see what happens there :)

      Point well taken on why the separators were around the $_.