regex - How do I find all elements of one array that are not present in another array? -


the answers found while researching point towards using grep, since arrays not longer 20-40 elements.

i have 2 arrays of filenames, @allfiles , @keepfiles. want delete files of filenames present in @allfiles. @allfiles has more elements @keepfiles.

i use like:

for(my $ii=0;$ii<=$allfilessize-1; $ii++)    {     # if current element of @allfiles not in @keepfiles, delete file     unless(grep(@allfiles->[$ii],@keepfiles))     {         $command = "del <value of @allfiles->[$ii]>";         system($command);     }  } 

i can't figure out how write grep statement. either don't know how reference value of array element correctly, or not write regex, or possibly both. or there better way this?

you can array_minus array::utils on cpan.

use strict; use warnings; use array::utils 'array_minus'; use data::printer;  @allfiles = ('a'..'z'); @keepfiles = qw(a e o u);  @delete_files = array_minus(@allfiles, @keepfiles);  p @delete_files; 

output:

[     [0]  "b",     [1]  "c",     [2]  "d",     [3]  "f",     [4]  "g",     [5]  "h",     [6]  "j",     [7]  "k",     [8]  "l",     [9]  "m",     [10] "n",     [11] "p",     [12] "q",     [13] "r",     [14] "s",     [15] "t",     [16] "v",     [17] "w",     [18] "x",     [19] "y",     [20] "z" ] 

alternatively can use lookup hash, common idiom in perl. build hash first , use exists keyword check if key present.

use strict; use warnings; use data::printer;  @allfiles = ('a'..'z'); @keepfiles = qw(a e o u);  %lookup = map { $_ => 1 } @keepfiles; @delete_files = grep { ! exists $lookup{$_} && $_ } @allfiles;  p @delete_files; 

output same above.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -