Win32 Perl - determining the difference between files and folders using the argument passed to the directory

I am writing a script in perl strawberry. The first thing to do is take the path argument and get a list of directories for that path, and it should be able to distinguish between files and folders. I read several guides on this issue and wrote a script below, but it only works when I give it the path that the script is currently in. If I give it any other way, the -f and -d tests do not work.

EDIT: Clarification: script Paste all the files and folders into @thefiles, if I give him a path different from his own, it's just the -f and -d tests that don't work.

use Getopt::Long; my $dir; GetOptions('-d=s' => \$dir); opendir(DIR, $dir) or die "BORKED"; @thefiles = readdir(DIR); print DIR; closedir(DIR); @filez; @dirz; foreach $file (@thefiles){ if (-f$file){ push(@filez, $file); } if (-d$file){ push(@dirz, $file); } } print "files: @filez \n"; print "Directories: @dirz \n"; 

Here is a screenshot: http://i.stack.imgur.com/RMmFz.jpg

Hope someone can help and thanks very much for your time. :)

+4
source share
2 answers

This is because the filetest -f and -d operators use a relative path unless you specify an absolute. The readdir function returns the names of the files (and subdirectories ...) found in the directory, but not the full paths.

From documents :

If you plan on filetest returning values ​​from readdir, you'd better add a directory to the question. Otherwise, because we are not chdir there, it would be testing the wrong file.

+1
source

martin clayton told you why your code is not working.

Here's how to fix it using map and some more modern Perl constructs:

 use strict; use warnings; use Getopt::Long; my $dir; GetOptions('-d=s' => \$dir); opendir my $dh, $dir or die "BORKED: $!"; my @thefiles = map { "$dir/$_" } readdir $dh; closedir $dh; my @filez; my @dirz; for my $file (@thefiles) { push @filez, $file if -f $file; push @dirz , $file if -d $file; } print "files: @filez \n"; print "Directories: @dirz \n"; 
+1
source

All Articles