Public
Snippet $1655248 authored by Jesse

Display a Linux system's uptime

Edited
linuxuptime.pl
#!/usr/bin/env perl
 
#################################################################################
# File: linuxuptime.pl
# Language: Perl
# Version: 2
# Author: culb (nightfrog)
# Contact: the01culb[at]gmail[dot]com
#
# Purpose: Output the uptime of Linux with a /proc/uptime file in a readable form
#
# ToDo: Use plurals for the units properly. Example, 1 seconds should be 1 second
#################################################################################
use strict;
use warnings;
 
## Open the /proc/uptime file
open( my $fh, '<', '/proc/uptime' ) or die 'Could not open file ' . '/proc/uptime.' . "\n" . $!;
 
## Retrieve the seconds section from the /proc/uptime file
my $uptime = ( split /\s+/, <$fh> )[0];
## Close the /proc/uptime file
close $fh;
 
my %hash;
## 1: $uptime has milliseconds appended to it after a decimal
##    int is the whole so subtracting them leaves the decimal( milliseconds )
## 2: The key is given the following name since sort is used later on
##    so this key needs to come after seconds
$hash{secondsmilli} = int( ($uptime - int $uptime)  * 1000 ) . 'milliseconds';
 
## These should be self-explanatory
$hash{seconds} = $uptime % 60 . 'seconds';
$hash{minutes} = $uptime / 60 % 60 . 'minutes';
$hash{hours} = $uptime / 3600 % 24 . 'hours';
$hash{days} = int( $uptime / 86400 ) . 'days';
 
## Output the values
print join( ' ', map{ $hash{$_} } grep{ $hash{$_} =~ /^[1-9]/ } sort keys %hash ) . "\n";
 
## Indicate a successful run
1;