Listing files sorted by creation time

Y

Yash

Hi,

I would like to do something with every text file from a directory,
with the latest created file taken first.
What is the best way to do this. I am looking for something like:

for my $file ( <something> glob("/mydir/*.txt") )
{
#my code
}

The glob will create an array of filenames. How do I make sure the
list comes in time order , latest fist?

Thanks
 
J

John W. Krahn

Yash said:
I would like to do something with every text file from a directory,
with the latest created file taken first.
What is the best way to do this. I am looking for something like:

for my $file ( <something> glob("/mydir/*.txt") )
{
#my code
}

The glob will create an array of filenames. How do I make sure the
list comes in time order , latest fist?

Of course *nix doesn't store the creation time anywhere but you can use
the time that the file was last maodified:

for my $file ( map $_->[1],
sort { $a->[0] <=> $b->[0] }
map [ -M, $_ ],
glob '/mydir/*.txt' )
{
#my code
}


John
 
J

John W. Krahn

Jim said:
On unix, you can do:

my @files = `cd /mydir;ls -t *.txt`;
^^^^^^^^^
You are changing the directory in a different process which means that
the list of file names returned will not be available from the current
directory and you didn't chomp the list so every file name will have a
newline at the end.
for my $file ( @files ) {
# your code
}


John
 
E

Eric Bohlman

John W. Krahn said:
Of course *nix doesn't store the creation time anywhere but you can use
the time that the file was last maodified:

Would that be the date of the file's last Cultural Revolution?
 
T

Tad McClellan

Yash said:
with the latest created file taken first.
^^^^^^^

Many filesystems (such as *nix) do not record the creation time.

Perl gives you access to 3 timestamps (perldoc -f stat), none
of them can be counted on to be the creation time.

The other followups I've seen in this thread use "modified"
where your spec said "created".
 
J

John W. Krahn

Jim said:
[QUOTE="John W. Krahn said:
On unix, you can do:

my @files = `cd /mydir;ls -t *.txt`;
^^^^^^^^^
You are changing the directory in a different process which means that
the list of file names returned will not be available from the current
directory and you didn't chomp the list so every file name will have a
newline at the end.

True, the above just gives you the file names. If you want the full
path name for the files you can do instead:

my @files = `ls -t /mydir/*.txt'[/QUOTE]

I think you meant:

chomp( my @files = `ls -t /mydir/*.txt` );



John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top