Removing elements from an array based on the second array

I have a list of file name prefixes in the @list1 and a list of full file names in the second @list2 array. In the end, I want to get a third array containing only the full file names that do not match the prefixes in @list1 . I started with:

 for my $match (@list1) { @list3 = grep { !/$match/ } @list2; } 

but he does not do what I thought it would do. What parameters do I need to get, I'm looking for.

+4
source share
3 answers

Perhaps an alternate regex would help:

 use strict; use warnings; my @list1 = qw/af c data gj/; my @list2 = qw/myfile.txt a.file.txt data.txt otherfile.txt jargon.txt/; my $regex = join '|', map "\Q$_\E", @list1; my @list3 = grep !/^(?:$regex)/, @list2; print "$_\n" for @list3; 

Output:

 myfile.txt otherfile.txt 
+5
source

If you want to use a more list-like style (as in your example), you can work with this:

 #!/usr/bin/env perl use strict; use warnings; use List::Util 'first'; use feature 'say'; my @filenames = qw(foo bar baz quux alice bob); my @forbidden = qw(f ba); my @matching = grep { my $filename = $_; not defined first { $filename =~ /^\Q$_/ } @forbidden; } @filenames; say for @matching; 

Output:

 quux alice bob 

Note I used first here instead of core- grep because with long @forbidden lists it can be more efficient since it stops after the first (and maybe only) match.

+1
source
 #!/usr/bin/perl use strict; use warnings; my @prefixes = qw(abd); my @items = qw(apple banana cow dog fruitcake orangutan crabcake deer); my @nonmatching; ITEMS: foreach my $item (@items) { foreach my $prefix (@prefixes) { next ITEMS if ($item =~ /^$prefix/) } push @nonmatching, $item } $,=$\="\n"; print @nonmatching; 

gives

 cow fruitcake orangutan crabcake 

Edited in accordance with the proposals of raina77ow.

0
source

Source: https://habr.com/ru/post/1447085/


All Articles