2

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

  • \d represents [0-9]

Why does it ignore minus at the beginning?

user4035
  • 22,508
  • 11
  • 59
  • 94

4 Answers4

7

You should match against the beginning of the string also with a ^:

if ($number =~ /^\d+/) {
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56
2

Minus is a symbol, not number, so use:

if ($number =~ /^-?\d+$/) {
    print $number;
}

-? say that minus - symbol can meet one or zero times

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
  • Maybe it would be better to use a capture group and print `$1`, otherwise this would be my prefered answer :) – hochl Feb 05 '14 at 09:36
  • Do you mean `/^-?(\d+)$/`? And where do you want to use `$1`? – Victor Bocharsky Feb 05 '14 at 09:39
  • No like `/^(-?\d+)/` and using `$1` to see what was matched, but whatever. – hochl Feb 05 '14 at 09:41
  • Ok, I add capture group :) but in `if` statement I think it isn't necessary – Victor Bocharsky Feb 05 '14 at 09:43
  • There're no needs to use a capture group in this case. It slows down the script. – Toto Feb 05 '14 at 09:45
  • Hmmm, only if you want to use the result in `print $1`. Actually I'm not entirely sure what the goal of the match in the OP question is :-/ If he doesn't use it the group slows down the match considerably. I just thought he wants to act on the matched data and thus including the `-` and `\d` in a group would have been a good idea, but re-reading the question I'm not that sure anymore. – hochl Feb 05 '14 at 09:45
  • I also probably do not fully understand, but I think you're right. I not know well how to use matches in Perl, I write on PHP – Victor Bocharsky Feb 05 '14 at 09:49
  • Ah ok. If you leave the print statement as is you'de have to remove the braces again (sorry for confusing oyu in the first place ^^) – hochl Feb 05 '14 at 09:53
1

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.

Borodin
  • 126,100
  • 9
  • 70
  • 144
0

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.

Jassi
  • 521
  • 6
  • 31