-1

I have this perl function that I would like call it after vmstat:

  sub insert_datetime{
        while($line = <>) {
         do
           print($line);
             if($line =~ /[0-9].*/)
             {
                 `date '+ %m-%d-%Y %H:%M:%S'`;
             }
             else
             {
                 print("\n")
             }
        }
}

wihin in perl when I call the vmstat command I would like to insert date field to each line as below:

 nohup `vmstat -Iwt 30 2884 | insert_datetime >vmstat_log &`;

I know that you need to back tick unix commands in perl. what if output of unix commands need to be pipe into a perl sub?

3
  • 1) SO is not a code writing service. 2) Would help if you said what it actually does. Date arithmetic? 3) DateTime can be used to do date arithmetic
    – ikegami
    May 3, 2013 at 20:22
  • Try writing something yourself and then if it doesn't work, bring it to us to help you along. You start it, we help. We don't write it for you. Show us the actual code that you've tried and then we can help you from there. Chances are you'll get pretty close to the answer if you just try it yourself first. May 3, 2013 at 21:03
  • @Andy Lester, I am really sorry. Yes you're right. I've updated my original post. May 3, 2013 at 21:16

1 Answer 1

1

It does not require much in the way of rocket science:

#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(strftime);

while (<>)
{
    chomp;
    $_ .= strftime(' %m-%d-%Y %H:%M:%S', localtime(time)) if ($_ !~ m/^\d/);
    print "$_\n";
}
4
  • @Jonathoan Leffler, I've created a sub cand called it latest and inserted your code in latest. when I do this vmstat -Iwt 30 | latest > vmstat.log & ; I get latest not found error. am I doing this right? May 3, 2013 at 21:09
  • 1
    Save the code as-is in a file called latest, and use chmod u+x latest
    – ikegami
    May 3, 2013 at 21:33
  • latest is a function in the perl script when I try to run: `nohup vmstat -Iwt 30 2884 | latest > vmstat_log', it does not work. The idea is, every time vmstat commands run, I need to insert datetime at the end of each line. when I run this, I get latest not found error. May 3, 2013 at 21:36
  • Shell scripts run commands, which are in general programs (when they aren't aliases or shell functions); programs are files. So, your latest must be a program that the shell can run; that, in turn, requires a file latest in a directory on your $PATH. If you want a shell function, you might create a function that contains the Perl script; it can probably be squished down to almost a single line, though personally, I'd not do that (but it seems that people like shell functions). May 3, 2013 at 21:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.