http://www.perlmonks.org?node_id=410615

Newbee21369 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to get the timestamp of a file in a directory. When I run the code shown below I get the following result.
Last change: Time::tm=ARRAY(0x200b6064)
How can I get the this format as my Result?
Last change: 2004111622
#!/usr/bin/perl use Time::localtime; $tm = localtime; opendir(DIR,"/usr/path"); my @dir=grep { !/^\.+$/ } readdir(DIR); closedir(DIR); $file_count = 0; foreach $file (@dir) { $mtime = (stat ($file))[9]; print "Last change:\t" . scalar localtime($mtime) . "\n"; }

2004-11-26 Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: Get file timestamp for a file in a directory
by steves (Curate) on Nov 26, 2004 at 19:28 UTC

    Yes, your use of Time::localtime is the key. It overrides the built-in localtime. If you use the built-in, it returns a ctime(3) like string. But in either case, a ctime string isn't going to give you that 2004111622 format in most cases. To get a specific date format, you'd also want to incorporate something like a call to the POSIX strftime function.

    I can't tell for sure, but it looks like you may also be trying to stat the base file name only: since you open the directory, you'd need to prepend the directory. Otherwise it will only work if you run it from that directory.

Re: Get file timestamp for a file in a directory
by ikegami (Patriarch) on Nov 26, 2004 at 19:07 UTC

    Change
    print "Last change:\t" . scalar localtime($mtime) . "\n";
    to
    print "Last change:\t" . ctime(localtime($mtime)) . "\n";
    as mention in the Time::localtime docs.

      Now that your post is readable, I'd like to correct myself. POSIX::strftime will suit your formating needs, and you need to add the path to the file you're stating for it to work properly. Here's working code:

      #!/usr/bin/perl use strict; use warnings; use POSIX (); my $dir = "/usr/path"; opendir(DIR, $dir); my @dir = grep { !/^\.+$/ } readdir(DIR); closedir(DIR); foreach (@dir) { my $file = "$dir/$_"; my $mtime = (stat($file))[9]; print "Last change:\t" . POSIX::strftime("%Y%m%d", localtime($mtime)) . "\n"; }
Re: Get file timestamp for a file in a directory
by steves (Curate) on Nov 26, 2004 at 19:03 UTC

    Surround your code with <code> </code> tags so we can read it.

Re: Get file timestamp for a file in a directory
by Newbee21369 (Novice) on Nov 27, 2004 at 16:45 UTC
    Thanks for all your help!