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

Hi,

I have a script that uses File::Find to recursively access directories and their contents.

The problem that I am facing in this is that when I have a list of directories in a directory, the find is accessing directories in an unexpected manner. I do not know the reason why.

The code snippet of my script is:-

#!/usr/bin/perl -w use strict; use File::Find; find(\&wanted,'/root/data'); sub wanted { if ($_=~ /^CPU-MEM/){ chdir($_); my $dir=cwd(); my @files=<$dir/*>; my $count=@files; if($count<4){ system('/usr/bin/perl /root/scripts/a.pl'); system('/usr/bin/perl /root/scripts/b.pl'); } chdir(".."); } }

Now, I have a directory data in which if i copy three directories - dir1 dir2 dir3. The processing is happening in this order:-

dir3 dir1 dir2

I want the recursion to occur in the same order as they are available in the data directory since there are dates in the subdirectories of data which must be printed in that order.

Is it possible to make File::Find perform my job as i require it to? If yes, How?

Thanks in advance for ur time.

Replies are listed 'Best First'.
Re: File::Find doubt
by choroba (Cardinal) on Apr 04, 2013 at 13:58 UTC
    Just use the preprocess option:
    find( { wanted => \&wanted, preprocess => sub { sort @_ }, }, '/root/data');
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thanks a lot...! :) Works very well...
Re: File::Find doubt
by ww (Archbishop) on Apr 04, 2013 at 14:49 UTC

    choroba's solution looks good -- nay, elegant -- assuming the directories you intend to scan are actually in an alphanumeric order. But if your desired order is:

    dir_ suba subb .... dir23 sub1 sub2 directoryA subdir0 subdir1 subdir11

    or some other scheme where an asciibetic order would be UNsatisfactory, then you may need to customize your plan.


    If you didn't program your executable by toggling in binary, it wasn't really programming!

Re: File::Find doubt
by Skeeve (Parson) on Apr 04, 2013 at 20:19 UTC

    You write:

    I want the recursion to occur in the same order as they are available in the data directory since there are dates in the subdirectories of data which must be printed in that order.

    But: There is no guaranteed "order" in a directory. So either you use the suggested solution posted here or, and that's what I usually do, you collect the paths you're interested in. Afterwards you process this collection in any order you feel fitting.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: File::Find doubt
by Anonymous Monk on Apr 04, 2013 at 15:32 UTC
    Coverage is promised ... order of occurrence is not.
Re: File::Find doubt
by Rahul6990 (Beadle) on Apr 05, 2013 at 06:01 UTC
    Agreed with Skeeve.
Re: File::Find doubt
by tc_blr (Novice) on Apr 05, 2013 at 09:23 UTC
    Thanks everybody for ur valuable inputs...