1

I'd like to create an array like this @exclude = ("[INFO] Reading file", "[INFO] All file(s) read"); which contains items that I would like to ignore while looping through another array

The other array is @nyuulog which I've ready into from a file and looks similar to this:

[INFO] Uploading 37 article(s) from 3 file(s) totalling 23.98 MiB```
[INFO] Reading file 157.1.1.par2...
[INFO] Reading file 159.1.1.rar...
[INFO] Reading file 159.1.1.vol0+1.par2...
[INFO] All file(s) read...
[INFO] Finished uploading 23.98 MiB in 00:00:16.083 (1527.03 KiB/s). Raw upload: 2613.34 KiB/s

So I'm using this:

foreach $line(@nyuulog) {print $txtfile("$line\n");}

which writes all of the lines but I'm wanting to not write lines out to the filehandle that contains an element in the @exclude array.

Is there an easy way to do this? I've tried numerous attempts at using grep or the new Perl ~~ command (which I don't think applies in this situation) and can't get the right combination of commands.

Any help or pointing me in the right direction - would be greatly appreciated.

Thank you

1
  • next if $line =~ /\Q...\E$/ might be sufficient to skip any "progress" type lines.
    – TLP
    Aug 22, 2020 at 12:52

2 Answers 2

2

Try this:

my $FilterRe = join("|", map({"(^\Q$_\E)"} @exclude));
my @Filtered = grep({!/$FilterRe/} @nyuulog);

Inspired by a question on perlmonks.

1
  • That did it - thank you so very much. I have no idea what the code is doing but what I wanted ends up in @Filtered and I will take some time to go through each step to understand it.
    – Todd
    Aug 21, 2020 at 3:13
2

Construct a look-up hash for what's to be excluded, and filter the array with it

my %excl = map { $_ => 1 } @exclude;

my @filtered = grep { not $excl{$_} } @original; 

This is about as efficient as list processing can be, O(N), and hopefully clear and easy.

Can also have it in a do block to avoid an extra variable (%excl) floating around

my @filtered = do { 
    my %excl = map { $_ => 1 } @exclude;
    grep { not $excl{$_} } @original;
};

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.