How to grep only multiple sets of five characters in any order in an array in a Perl program?
@arr2 = grep(/[BCRZ]+/, @arr1);
@arr1 can contain
CRZBBZTCCBBRZ
FJDLSFJSLFJS
CRZBBZCCBBRZ
only the lines like the last should be taken
If what is you want is lines that only contain the 5 chars and none others, then a regex like:
/^[BRCZW]+$/
looks for strings containing one or more of your 5-character set, but containing no other characters. But it might be more efficient to us @carol's solution using grep(). Which uses a regex to determine if the string has any of the unwanted characters, and then rejects that line.
grep. How were you suggesting it could be used instead?I think this may do what you want. It rejects a string if it contains any character other than CBRZW.
use strict;
use warnings;
my @arr1 = qw/ CRZBBZTCCBBRZ FJDLSFJSLFJS CRZBBZCCBBRZ /;
my @arr2 = grep { not /[^CBRZW]/ } @arr1;
print "$_\n" for @arr2;
output
CRZBBZCCBBRZ
not and the ^ in the character class. Another way you could do this is with grep { /^[BCRZ]+$/ } @arr1; - one or more characters from that class between the start and end of the string.CBRZW. Also, the code produces the output that you requested.
BCRZ?