http://www.perlmonks.org?node_id=930140


in reply to regex not working

Well let's see what your program does:

$ perl -le' use warnings; use strict; print "Enter number : "; chomp( my $num = <STDIN> ); print "\$num = $num"; my @nums = split /(?<=[\d])/, $num; print "\@nums = @nums"; my $i = 0; for ( @nums ) { my $regex = qr/[$i]{$_}/; print "\$regex = $regex"; print $num =~ $regex ? "true" : "false"; $i++; } ' Enter number : 2020 $num = 2020 @nums = 2 0 2 0 $regex = (?-xism:[0]{2}) false $regex = (?-xism:[1]{0}) true $regex = (?-xism:[2]{2}) false $regex = (?-xism:[3]{0}) true

On the first pass you are trying to match '2020' with /[0]{2}/, or in other words with /00/.    Since '2020' does not contain the string '00' the program prints false.

On the second pass you are trying to match '2020' with /[1]{0}/, or in other words with //.    Since '2020' contains five places that will match the program prints true.

$ perl -le'$x = () = "2020" =~ /[1]{0}/g; print $x' 5

The next two follow the same pattern as the first two.