Tuesday, April 29, 2008

Converting seconds to Hours, Minutes & Seconds

It's amazing how many different approaches to doing this you can find on the web.

Some of them are really tortured and inefficient!

These are the tightest two I've found:


#!/usr/bin/perl
#
#
#
use warnings;
use strict;

my $time = time % 86400;

#
# http://www.perlmonks.org/?node_id=101511
#
printf "%02d:%02d:%02d\n",(gmtime $time)[2,1,0];

#
# http://www.perlmonks.org/?node_id=101548
#
printf "%02d:%02d:%02d\n", ($time/3600)%24, ($time/60)%60, $time%60;


To convert the other way, an easy way is to use POSIX mktime:


#!/usr/bin/perl

use warnings;
use strict;

use POSIX qw(mktime);

my $day = "2008-05-28";
my ($d_year, $d_mon, $d_mday) = split /-/, $day;

my $secs = mktime(0, 0, 0, $d_mday, $d_mon-1, $d_year-1900);

Wednesday, April 02, 2008

Showing a function in ksh

If you need to see the contents of a function in ksh...


$ typeset -f [FUNCTION_NAME]


if you do typeset -f by itself it will list all of the defined functions.