Skip to content

Instantly share code, notes, and snippets.

@wh13371
Created February 26, 2016 19:08
Show Gist options
  • Save wh13371/5de280d5a0ba0fb45649 to your computer and use it in GitHub Desktop.
Save wh13371/5de280d5a0ba0fb45649 to your computer and use it in GitHub Desktop.
perl - tee
#! /usr/bin/perl
# usage: ping 8.8.8.8 | tea.pl [-v] [-t] [FILE]
# -v = verbose | -t = prefix timestamp to output | FILE = output filename
use IO::Handle;
use Getopt::Long;
use Time::HiRes;
use POSIX;
sub cmd_args
{
GetOptions("time|t", \$time, "verbose|v", \$verbose) or die $!;
}
sub now
{
my ($secs, $us) = Time::HiRes::gettimeofday;
my $dt = strftime(q/%Y-%m-%d %H:%M:%S./, localtime($secs)) . sprintf("%06d", $us);
return $dt;
}
sub main
{
$f = $ARGV[0] || "tea." . $^T . ".log"; # create an epoch padded filename if ARGV is null
open OUT, '>', $f || die "$!\n";
OUT->autoflush(1);
while (<STDIN>)
{
if ($time)
{
if (! /\S/)
{
print $_; # <-t> enabled but do not prefix <blank> lines
print OUT $_; # <-t> enabled but do not prefix <blank> lines
}
else
{
print now() . ": " . $_; # to STDOUT with timestamp prefix
print OUT now() . ": " . $_; # to FILE with timestamp prefix
}
}
else # [-t] not enabled - output to STDOUT & FILE verbatum
{
print $_;
print OUT $_;
}
}
close OUT;
}
cmd_args;
main;
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment