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

I am trying to extract the year yyyy of a file created on a Unix system. I am taking the files in a directory and according to the year of the file place them in a folder named for the year of the file. IF I do a system ls -l it give me a filed for year unless it is a file that is less than a year old then it just gives me the time, month and day, it could be 2006 or 2007. Got to be an easy way to get just the year of the file. Thank You

Replies are listed 'Best First'.
Re: extracting year of a file
by Zaxo (Archbishop) on Feb 02, 2007 at 21:49 UTC

    You can use stat and POSIX::strftime() to extract the mtime year. I think mtime is the proper concept, since in a way it is when the file was created in its current form.

    Here's a small demo:

    $ cat >foo.txt [Ctrl-D] $ perl -MPOSIX=strftime -e'print strftime("%Y\n", > localtime((stat "foo.txt")[9]))' 2007 $
    That gives you the year as a string, but you can add zero to that if you want it taken as a number.

    After Compline,
    Zaxo

      And since the POSIX module exports its functions by default, you can just say:
      $ perl -MPOSIX -e'...'
      (or just  use POSIX; in a longer perl script).
Re: extracting year of a file
by kyle (Abbot) on Feb 02, 2007 at 21:57 UTC

    You can use stat to get the last modification time (that's what ls reports) and then localtime to find out what year that was.

    my $filename = 'your_file_name_here'; my $mtime = (stat $filename)[9]; my $year = (localtime $mtime)[5] + 1900;
Re: extracting year of a file
by Joost (Canon) on Feb 02, 2007 at 21:31 UTC