Slower certinally, OP's fixed code is about 3x faster than using similar File::Find code.
Rate FileFind FixedOP FileFind 163/s -- -70% FixedOP 546/s 235% --
use File::Find; use File::stat; use strict; use Benchmark qw(:all); my $dirname = './'; my $oldestfile; my $filename; cmpthese (-2, {'FixedOP' => 'op ();', 'FileFind' => 'ff ()'}); sub op { $oldestfile = 0; $filename = "No BOT REPORT: ERROR"; opendir(DIR, $dirname) or die "can't opendir $dirname: $!"; while (my $file = readdir(DIR)) { if ($file =~ /\.txt$/) { my $x = stat($dirname.$file)->mtime (); if ( $x > $oldestfile) { $oldestfile = $x; $filename = $file; } } } #print "Oldest file >$filename< last touched $oldestfile\n"; closedir(DIR); } sub ff { $oldestfile = 0; $filename = "No BOT REPORT: ERROR"; find (\&search, $dirname); #print "Oldest file >$filename< last touched $oldestfile\n"; sub search { if (-d $File::Find::name) { $File::Find::prune = 1 if $File::Find::name ne '.'; return; } return if $File::Find::name !~ /\.txt$/; return if (my $x = stat($File::Find::name)->mtime ()) <= $oldestfile +; $oldestfile = $x; $filename = $File::Find::name; } }
4x more work? Well 19 lines versus 19 lines doesn't look like 4x more work to me (I did change formating to my style, but even using K&R the difference is not great - 16 versus 17).
Actually, in my initial answer to you I should also have said: "To make the OP, and any others reading this thread for enlightenment, aware of another way to do it.
I'm sure that OP fixed his problem using the information in the first part of my node or the same information from one of the other replies. However if he finds that he needs to search a list of directories or sub-directories, OP is now aware of a tool that will make that easier.
In reply to Re^5: Finding Oldest File in a Directory
by GrandFather
in thread Finding Oldest File in a Directory
by awohld
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |