First. Your regexp is slightly wrong. It matches even strings like 'hello there 1d'. You would need one more (?:...) around the whole regexp except the ^ and $ to fix it. Currently the first alternative matches only at the start of the string, while the second only at the end. You want them to only match the whole string.
Anyway I would suggest something like this:
while (<STDIN>) {
chomp;
if ($_ and /^(?:(\d+)d)?(?:\s*(\d+)h)?$/i) {
print "Days: $1, Hours: $2\n";
} else {
print "Doesn't match\n";
}
}
The
$_ and ... is necessary to prevent an empty string from matching, the rest is taken care of by the regexp.
Jenda
Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.
-- Rick Osborne
Edit by castaway: Closed small tag in signature