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

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

Hail fellow Monks,
I am currently trying to read through directories recursively. I have this down, but I came across a weird situation that I thought you may be able to help me with. The code for reading the directories is basic, but it works:
my $dir = "../data/ifx/reports/"; opendir (DIR, $dir) or die "cannot opendir $dir"; foreach my $file (readdir(DIR)) { if(($file eq ".") || ($file eq "..")) {} else { print $file."<BR>"; &Read_Next_Dir ($file); } } closedir (DIR); sub Read_Next_Dir { my $param = $_[0]; my $dir = "../data/ifx/reports/".$param."/"; opendir (DIR, $dir) or die "cannot opendir $dir"; foreach my $file (readdir(DIR)) { if(($file eq ".") || ($file eq "..")) {} else { print "---->";print $file."<BR>"; &Read_Report_Dir ($file, $param); } } closedir (DIR); } sub Read_Report_Dir { my @report_array; my $report_name = $_[0]; my $param = $_[1]; my $dir = "../data/ifx/reports/".$param."/".$report_name."/"; opendir (DIR, $dir) or die "cannot opendir $dir"; foreach my $file (readdir(DIR)) { if(($file eq ".") || ($file eq "..")) {} else { print "--------->"; print $file."<BR>"; push(@report_array,$file); } } foreach my $unsorted_file(@report_array) { print $unsorted_file; } @report_array = sort {$a cmp $b} @report_array; foreach my $sorted_file(@report_array) { print $sorted_file."<BR>"; } closedir (DIR); }
The results it prints out are as follows:
103 ---->137 --------->Y2001.pdf --------->Q2001-1.pdf --------->Q2001-2.pdf --------->M2001-12.pdf --------->M2001-11.pdf --------->M2001-01.pdf
Y2001.pdfQ2001-1.pdfQ2001-2.pdfM2001-12.pdfM2001-11.pdfM2001-01.pdfM2001-01.pdf
M2001-11.pdf M2001-12.pdf Q2001-1.pdf Q2001-2.pdf Y2001.pdf ---->142 --------->M2001-01.pdf --------->M2001-11.pdf --------->M2001-12.pdf --------->Q2001-1.pdf --------->Q2001-2.pdf --------->Y2001.pdf
M2001-01.pdfM2001-11.pdfM2001-12.pdfQ2001-1.pdfQ2001-2.pdfY2001.pdfM2001-01.pdf
M2001-11.pdf M2001-12.pdf Q2001-1.pdf Q2001-2.pdf Y2001.pdf 107 ---->137 --------->M2001-01.pdf --------->M2001-11.pdf --------->M2001-12.pdf --------->Q2001-1.pdf --------->Q2001-2.pdf --------->Y2001.pdf M2001-01.pdfM2001-11.pdfM2001-12.pdfQ2001-1.pdfQ2001-2.pdfY2001.pdfM20 +01-01.pdf M2001-11.pdf M2001-12.pdf Q2001-1.pdf Q2001-2.pdf Y2001.pdf ---->142 --------->M2001-01.pdf --------->M2001-11.pdf --------->M2001-12.pdf --------->Q2001-1.pdf --------->Q2001-2.pdf --------->Y2001.pdf M2001-01.pdfM2001-11.pdfM2001-12.pdfQ2001-1.pdfQ2001-2.pdfY2001.pdfM20 +01-01.pdf M2001-11.pdf M2001-12.pdf Q2001-1.pdf Q2001-2.pdf Y2001.pdf
I guess my question is why do the two bolded results differ. The files in the directories are the same. Shouldn't they be read in, in the same order, each time I do a readdir()??
Any help would be appreciated.

Prince99

Too Much is never enough...