Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 193
  • Last Modified:

-d and Find::File::name

Hi,
   I have this snippet of code in which I am trying to print out all the directories. It does not work using the -d, but -f does print all the files. Why doesn't -d work for directories? What am I doing wrong? This should be a pretty basic question for an experienced Perl programmer.

<code>

use strict;
use File::Find;

sub wanted
{  
   if (-d $File::Find::name)
   {    
      print "$File::Find::name\n";
   }
}

find(\&wanted, 'C:/');

</code>

many thanks,

Barry

0
titanandrews
Asked:
titanandrews
1 Solution
 
TintinCommented:
use strict;
use File::Find;

sub wanted
{  
   print "$File::Find::name\n" if -d;
}

find(\&wanted, 'C:/');
0
 
PC_User321Commented:
>>  What am I doing wrong?

Your program works for -f and for -d.
But if you specify a relative path (eg '.') instead of the absolute 'c:/' then the program does not work as expected.  The reason is that 'wanted' changes to the current directory as it tunnels through the directory structure.
So if the program started in '.' (which happens to be c:/) then when it gets to WinNT and asks "Is ./WinNt/System32 a valid directory" the answer will obviously be 'No'.

If you change your 'if' line to
   if (-d $_)
(which if equivalent to 'if (-d)')  
then everything will work because, for example, when in WinNT the question will be "Is System32 a valid directory", and the answer will obviously be 'Yes'.
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now