I have the following perl code with a string that I'm needing to check against several cases in order to decide what to do with it. None of them work. Code looks like this:
my $param = "02 1999";
my @months = qw(january february march april may june july august september october november december);
my $white = /^s*$/; #check if all whitespace
my $singleyear = /^d{2,4}$/; #check if 2-4 digits
my $nummonth = /^d{1,2}sd{1,4}$/; #check if 1-2 digits then 1-4
if ($param =~ $white) {
my($day, $month, $year)=(localtime)[3,4,5];
my $monthname = $months[$month];
print "$monthname $year
";
}
if ($param =~ $singleyear) {
print "$param
";
}
if ($param =~ $nummonth) {
my $monthnumber = $param =~ /^d{1,2}/; #grabs the number at the front of the string
my $monthstring = $months[$monthnumber];
my $yearnumber = $param =~ /(d{1,4})$/; #grab second number, it does this wrong
print "$monthstring $yearnumber
";
}
Given the above, the output should simply be:
february 1999
Instead, the output is:
3 118
02 1999
february 1 #this only grabbed the first digit for some reason.
So ALL of the cases evaluated as true for some reason, and the capture on the year didn't even work. What am I doing wrong? Testing all of my regex at regex101 worked fine, but not in the script.
See Question&Answers more detail:os