Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Perl's grep function work with a regex?

Tags:

regex

grep

perl

How does the following grep function works (what does !/0o1Iil]/ do? )

@chars = grep !/0o1Iil]/, 0..9, "A".."Z", "a".."z"; 
use Data::Dumper; 
print Dumper @chars;

to produce the following in @chars?

$VAR1 = 0;
$VAR2 = 1;
$VAR3 = 2;
$VAR4 = 3;
$VAR5 = 4;
$VAR6 = 5;
$VAR7 = 6;
$VAR8 = 7;
$VAR9 = 8;
$VAR10 = 9;
$VAR11 = 'A';
$VAR12 = 'B';
$VAR13 = 'C';
$VAR14 = 'D';
$VAR15 = 'E';
$VAR16 = 'F';
$VAR17 = 'G';
$VAR18 = 'H';
$VAR19 = 'I';
$VAR20 = 'J';
$VAR21 = 'K';
$VAR22 = 'L';
$VAR23 = 'M';
$VAR24 = 'N';
$VAR25 = 'O';
$VAR26 = 'P';
$VAR27 = 'Q';
$VAR28 = 'R';
$VAR29 = 'S';
$VAR30 = 'T';
$VAR31 = 'U';
$VAR32 = 'V';
$VAR33 = 'W';
$VAR34 = 'X';
$VAR35 = 'Y';
$VAR36 = 'Z';
$VAR37 = 'a';
$VAR38 = 'b';
$VAR39 = 'c';
$VAR40 = 'd';
$VAR41 = 'e';
$VAR42 = 'f';
$VAR43 = 'g';
$VAR44 = 'h';
$VAR45 = 'i';
$VAR46 = 'j';
$VAR47 = 'k';
$VAR48 = 'l';
$VAR49 = 'm';
$VAR50 = 'n';
$VAR51 = 'o';
$VAR52 = 'p';
$VAR53 = 'q';
$VAR54 = 'r';
$VAR55 = 's';
$VAR56 = 't';
$VAR57 = 'u';
$VAR58 = 'v';
$VAR59 = 'w';
 $VAR60 = 'x';
 $VAR61 = 'y';
 $VAR62 = 'z';
like image 961
Lydon Ch Avatar asked Jan 22 '23 10:01

Lydon Ch


1 Answers

Here's the grep perldoc. The statement in your example is using the grep EXPR,LIST syntax, which means any Perl expression can take the place of EXPR.

grep takes the list provided to it, and returns only the items where EXPR is true.

EXPR in this case is ! /0o1Iil]/ (space added for readability) which means "this item is not matched by the regex /0o1Iil]/. Since none of those items are matched by that regular expression (none of them contain the string 0o1Iil]) they are all returned.

As other posters have mentioned, the regex was probably supposed to read /[0o1Iil]/, which would remove characters that could be confused, e.g. 0 and o, 1 and I. This sounds useful for passwords or serial numbers, etc.

Btw, you could rewrite the grep into the clearer BLOCK form, and make the LIST construction explicit:

@chars = grep { ! /[0o1Iil]/ } (0..9, 'A'..'Z', 'a'..'z');
like image 190
rjh Avatar answered Jan 24 '23 22:01

rjh