What am I missing in perlre

J

janfure

I wrote a script for detecting alphabetical/non numeric characters:

#!/usr/local/bin/perl -w
use strict;
$_ = '2 3';
if ($_ =~ m/\D/x){
print "$_ has non numerical character(s)!\n";
}
$_ = '2A 3';
if ($_ =~ m/\D/x){
print "$_ has non numerical character(s)!\n";
}

This script does not do what I expected, the presence of the space in
the string seems to cause a match with /\D/x, despite the 'x' modifier,
which causes the regex engine to ignore MOST whitespace, but maybe not
the one that mattered to me.

This script (stripping out spaces from $_) does what I expected the
first one to do:

#!/usr/local/bin/perl -w
use strict;
$_ = '2 3';
$_ =~ s/\s+//g;
if ($_ =~ m/\D/){
print "$_ has non numerical character(s)!\n";
}
$_ = '2A 3';
$_ =~ s/\s+//g;
if ($_ =~ m/\D/){
print "$_ has non numerical character(s)!\n";
}

What am I missing, is there a better way to match alphabetical letters
than /\D/x?

Jan
 
S

Sherm Pendley

I wrote a script for detecting alphabetical/non numeric characters:

#!/usr/local/bin/perl -w
use strict;
$_ = '2 3';
if ($_ =~ m/\D/x){
print "$_ has non numerical character(s)!\n";
}
$_ = '2A 3';
if ($_ =~ m/\D/x){
print "$_ has non numerical character(s)!\n";
}

This script does not do what I expected, the presence of the space in
the string seems to cause a match with /\D/x, despite the 'x' modifier,
which causes the regex engine to ignore MOST whitespace

The 'x' modifier ignores whitespace and comments *in the pattern*, not in
the target string. It allows you to write stuff like this:

m/
\w # One alphanumeric character
\d* # Followed by zero or more digits
/x;
What am I missing, is there a better way to match alphabetical letters
than /\D/x?

m/[[:alpha:]]/;

sherm--
 
T

Tad McClellan

#!/usr/local/bin/perl -w

use warnings; # the modern way, much better than -w


if ($_ =~ m/\D/x){
This script does not do what I expected, the presence of the space in
the string seems to cause a match with /\D/x,


Yes, because space _is_ a non-digit character.

despite the 'x' modifier,
which causes the regex engine to ignore MOST whitespace,


*in the pattern*. (not in the string that the pattern is to match against)

spaces are ignored in the _pattern_

m/ \D /x

is equivalent to writing the pattern the way you originally did.

The m//x modifier does not change the meaning of any of
the regex backslash escape shortcuts.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top