Skip to content

Instantly share code, notes, and snippets.

@afresh1
Last active December 22, 2021 22:14
Show Gist options
  • Save afresh1/27015e1e9fadebaab4b5ae0809d96e42 to your computer and use it in GitHub Desktop.
Save afresh1/27015e1e9fadebaab4b5ae0809d96e42 to your computer and use it in GitHub Desktop.
A perl implementation of "tee" that prefixes each line to the teed file with a timestamp relative to the start of ths script.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
use Time::HiRes qw< gettimeofday tv_interval >;
# Copyright (c) 2020 Andrew Hewus Fresh <andrew@afresh1.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
my $mode = '>';
while ( @ARGV && ( my ($opt, $rest) = $ARGV[0] =~ /^-(.)(.*)$/ ) ) {
if ( $ARGV[0] eq '--' ) {
shift @ARGV;
last;
}
elsif ( $opt eq 'a' ) {
$mode = '>>';
}
elsif ( $opt eq 'i' ) {
$SIG{INT} = 'IGNORE';
}
else {
die "teetime: unknown option -- $opt\n"
. "usage: teetime [-ai] [file ...]\n";
}
if ($rest) {
($opt, $rest) = $rest =~ /(.)(.*)/;
redo;
}
else {
shift @ARGV;
}
}
my @fh;
for (@ARGV) {
open my $fh, $mode, $_ or die "Unable to open $_: $!";
$fh->autoflush;
push @fh, $fh;
}
STDOUT->autoflush;
my $start = [gettimeofday];
while ( my $line = readline(STDIN) ) {
STDOUT->print($line);
$line = sprintf "%012.3f %s", tv_interval($start), $line;
$_->print($line) for @fh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment