I have a quick question. What am I doing wrong in below code:
#!/usr/bin/perl -w
use strict;
my $num = "12345";
print "$num \n" if $num =~ m/\d{1,3}/;
As my number is 5 digits long, I was hoping that the output should not print anything because if statement is looking for a number with at least 1 digit and maximum 3 digits. But my script pints the output as below:
# perl num.pl
12345
Am I misunderstanding the above regex?
Thanks.
EDIT:
So ,Actually I am trying to match an IP address like string. e.g. i want to match 11.222.3.444 but it did not work with m/\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}/
so i started working on a single string containing only the number and hence then posted this on the stack overflow.
If i have to put ^ OR $ then how should i go about using them if I want to match IP address like string s mentioned above.
Thanks for you time.
What your perl code says is, “inside the string $num can you find a string at least 1 character at most 3 characters made only of numbers.” The answer of course is yes.
What you want is
print "$num \n" if $num =~ m/^\d{1,3}$/;Which means “inside the string $num starting at the first character and going to the last character is there a string at least 1 character long at most 3 characters long made only of numbers.”
If you are trying to find something like an ip address
regexp to match IP address is a good discussion of how to do that.