backscratcher

 

perlsnips

Page history last edited by tbarron 1 yr ago

Using Socket routines

 

use Socket; # # inet_aton converts a name (long or short) or an IP address in string # format into a 4 byte structure containing the IP address, one octect # per byte # $x = inet_aton("myhost"); $y = inet_aton("myhost.fully.qualified.name"); $z = inet_aton("123.456.123.456"); # # We can use unpack to see what's in the four byte structures # print join(".", unpack('C4', $x)); print join(".", unpack('C4', $y)); print join(".", unpack('C4', $z)); # # We can retrieve the string format IP address using inet_ntoa # print inet_ntoa($x); print inet_ntoa($y); print inet_ntoa($z); # # Even simpler: to get a name from an IP address: # $ip = inet_aton("123.123.123.123") $name = gethostbyaddr($ip, AF_INET) # # To get a (human-readable) IP address from a name: # $ip = inet_ntoa(gethostbyname("myhostname"))

 

Times

 

Parse a time from a string


#
# usage: $when = parse_time("Wed Jan 16 15:31:17 EST 2008")
#        $when == "15:31:17"
#
sub parse_time
{  
   my ($rval, $s);
   ($s) = @_;
   ($rval) = ($s =~ /(dd:dd:dd)/);
   return $rval;
}

 

Convert H:M:S to seconds


#
# usage: $seconds = hmstos("03:07:25")
#
sub hmstos
{  
   my ($h, $hms, $m, $rval, $s);
   ($hms) = @_;
   ($h, $m, $s) = ($hms =~ /(dd):(dd):(dd)/);
   $rval = $s + 60*($m + 60*$h);
}

 

Convert seconds to H:M:S


#
# usage: $hms = stohms(3600)
#        $hms -> "01:00:00"
#
sub stohms
{  
   ($s) = @_;
   $m = int($s/60);
   $s = $s % 60;
   $h = int($m/60);
   $m = $m % 60;
   $rval = sprintf("%d:%02d:%02d", $h, $m, $s);
}

Comments (0)

You don't have permission to comment on this page.