简体   繁体   中英

Capturing output from a shell command without [also] sending its output to stdout

I am writing a Perl program to get the modified time of a particular file. I have tried the following scenarios:

  1. $time = system("stat -c %y temp.txt") --> this sets $time to "0" and writes "2013-04-03 06:10:02.000000000 -0600" to stdout.

  2. $time = `stat -c %y temp.txt` --> this sets $time to "2013-04-03 06:10:02.000000000 -0600" and also displays the same thing ("2013-04-03 06:10:02.000000000 -0600") on stdout.

  3. $time = exec("stat -c %y temp.txt") --> this does not set $time but prints "2013-04-03 06:10:02.000000000 -0600" on stdout.

As this is flooding my stdout with the same type of data again and again, I want to get rid of it. Can please somebody help me in this?

You'd be better off using perl's built-in stat function:

@st = stat('temp.txt');

$st[9] now contains the Unix epoch timestamp for the last-modified time. You could get it into a more useful format like this

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($st[9]);

or just get a printable string like this

$time = localtime($st[9]);

Backticks (and the related qx operator or readpipe function) do not write any output on standard output; they execute a command, capture the command's output and return it (usually to assign it to some variable). So

$time = `stat -c %y temp.txt`

will set $time and not write anything to standard output. It is possible for the command to write something to standard error, but from the symptoms you describe, it doesn't look like that is what's happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM