Short answer: perl -e "printf qq{%02d:%02d:%02d\n},
(localtime(time))[2,1,0];"

Longer answer: printf works by taking a template, enclosed in qoutes ( the
qq{%02d:%02d:%02d\n} part.  I subed qq{} for regular double qoutes for
command line use.) followed by a comma, and then the variables(or strings)
that will "populate" the template in the same order.  In a nutshell, the %
sign tells perl that this starts a fillin field, then a number indicating
the length of the string ( the leading zero is how you pad with zeros to the
left), and finally, the datatype.  In this case the "d" stands for digit.
"s" stands for a regular string, "f" stands for floating point, etc.  Check
the documentation for the printf and sprintf functions, they are your
friends!  Finally, the (localtime(time)) returns a list, which I then use a
slice to "carve" the parts I need.



<snip>

Basic code would be like this :

my
($nowsec,$nowmin,$nowhour,$nowmday,$nowmon,$nowyear,$nowwday,$nowyday,$nowis
dst) = localtime(time());
print "$nowhour:$nowmin:$nowsec\n" ;


But this raw code will display for instance
14:06:02
like this
14:6:2


so here is some code that will correctly display units 9 and below  :



my
($nowsec,$nowmin,$nowhour,$nowmday,$nowmon,$nowyear,$nowwday,$nowyday,$nowis
dst) = localtime(time());
($hour,$min,$sec) = ($nowhour,$nowmin,$nowsec) ;

foreach ('hour','min','sec') {
        ${$_}= '0' . ${$_} if ${$_} < 10  ;
        }

print "$hour:$min:$sec\n" ;



(note the use of only one 'my')

Which is all really equivalent, for clarity's sake to :



my
($nowsec,$nowmin,$nowhour,$nowmday,$nowmon,$nowyear,$nowwday,$nowyday,$nowis
dst) = localtime(time());
my ($hour,$min,$sec) = ($nowhour,$nowmin,$nowsec) ;

$hour = '0' . $hour if $hour < 10  ;
$min  = '0' . $min  if $min  < 10  ;
$sec  = '0' . $sec  if $sec  < 10  ;

print "$hour:$min:$sec\n" ;


Regards.

_____________________________________________
Bruno Bellenger
Sr. Network/Systems Administrator


<snip>

I would highly suggest not learning to create code this way.  While it may
be fine for this "example", there are much better (more lazy, more
impatient, and certainly more hubris) ways to get the right result.  In this
case, you create all the data, but what if you need to have the data input
by a user?  What if you later need to use the "non" zeroed variable?   While
this will arrive at the "correct" answer, in my opinion, this is not a good
solution.

Joe

_______________________________________________
Perl-Win32-Admin mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to