Skip to content

Instantly share code, notes, and snippets.

@asciidisco
Created January 3, 2014 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asciidisco/8241400 to your computer and use it in GitHub Desktop.
Save asciidisco/8241400 to your computer and use it in GitHub Desktop.
Converting this line of perl to javascript...
@{$hashQ->{apIDs}}=grep !/$id/,@{$hashQ->{apIDs}};
@migg24
Copy link

migg24 commented Jan 3, 2014

My PERL is very rusty, but I would say that this line is an array filter, which filters out the ID $id from the array in $hashQ->{apIDs}. Some context would be useful. So something like this in JS assuming the variable "id" is int or string, hashQ is an object and hashQ.apIDs an array:

hashQ.apIDs = hashQ.apIDs.filter(function(elem) {
    return !elem.match(new RegExp(id));
});

Maybe the regex is not needed in JS because a "return elem !== id" may also work. Depends on what is inside the array. I used "new Regexp" because the id is a variable.

Warning: this is untested :)

@Su-Shee
Copy link

Su-Shee commented Jan 3, 2014

That's a lot of concept in one line:

a) grep /stuff/ @{ ... } greps for stuff in the array which is referenced in the hash by the key apIDs

b) this is filtered by stuff NOT in said array and re-assigned as the same key referencing an array again.

So it filters aus non-existing IDs from apIDs and creates a new list for apIDs - but in a somewhat nested data structure.

In general, the grep construct is extremely common to filter things.

In more lines:

my @ids = @{ $hashQ->{apIDs} };

my @filtered_ids = grep { !$id } @ids;

$hashQ->{apIDs} = @filtered_ids;

@asciidisco
Copy link
Author

\o/ Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment