Tuesday, February 10, 2009

Perl: file or directory

To check this, the prescription says:

  1. if (-d $file)  
  2. {  
  3.    print $file." is a directory\n";  
  4. else {  
  5.    print $file." is a file\n";  
  6. }  


When this is used in pair with IO:Dir, which helps you to enumerate contents of a given directory, one non-obvious step should not be forgotten:

  1. tie %dir'IO::Dir'$dir;  
  2. foreach my $entry(keys %dir) {  
  3.    next if ($entry eq '.' or $entry eq '..');  
  4.    # important part is here: concatenation with the full path  
  5.    if (-d $dir."/".$entry)  
  6.    {  
  7.       print $entry." is a directory\n";  
  8.    }  
  9. }  

2 comments:

Anonymous said...

Before declaring $file to be a file, you may also want to test (-f $file) to verify that it is in fact a regular file. Especially if you're on a unix-type system, where it could be a symbolic link, device node, etc. which are neither directories nor (regular) files.

Dmitry Kan said...

Thanks, Dave, that is an excellent addition.