Have you checked whether they space is already in $h when you get into the sub? If so, your check of the length will not append a "0" (neither will sprintf for that matter. You could check this by adding a debuggin line to the sub
print "($h).($m).($s)\n" before your set of if statements.
Once that issue is resolved, a simple
substr('00000000',-$h,-$len) serves for formatting. I usually set the string of zeroes to be as long as I need to cover all formats then set $len to the size I need.
Alternately, if the possibility of the space cannot be eliminated before the formatting function call, you could use this regex
$h =~ s/\s*(\d+)/substr(('0' x 8).$1,-$len)/e;
PJ
unspoken but ever present -- use strict; use warnings; use diagnostics; (if needed)