Reputation: 23749
I faced behaviour of Perl, that I can't explain:
#!/usr/bin/perl
use strict;
use warnings;
my $number = -10;
if ($number =~ /\d+/) {
print $number;
}
This prints -10
, despite the fact, that
Why does it ignore minus at the beginning?
Upvotes: 2
Views: 298
Reputation: 126742
You can write this as
if ($number and $number !~ /\D/) {
print $number;
}
which checks that the string isn't zero-length and doesn't contain any non-digit characters.
Upvotes: 1
Reputation: 12306
Minus is a symbol, not number, so use:
if ($number =~ /^-?\d+$/) {
print $number;
}
-?
say that minus -
symbol can meet one or zero times
Upvotes: 2
Reputation: 541
Whatever is the purpose of \d+ or [0-9]+ , its doing correct thing only. It depends upon your requirement what else you want like mixture of integers or just negative number to match or positive number to match or beginning, end, anywhere etc. All depends upon the pattern you want to develop.
Upvotes: 0
Reputation: 13725
You should match against the beginning of the string also with a ^:
if ($number =~ /^\d+/) {
Upvotes: 7