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

Anyone have any idea why the -f and -d operators are not working properly here:

Section 1: the code

Section 2: what is in the directory using ls -l

Section 3: what the code outputs.

Section 1: =========================================================

use strict; use gfrmGlobals; my @files = (); my $flNm = ""; opendir (DIR, $GCdfltDBexpPrmPthNm) || die "can't open directory\n"; @files = readdir(DIR); closedir (DIR); foreach $flNm (@files) { if ( -f $flNm) { print "is a file: $flNm\n"; } elsif ( -d $flNm) { print "is a dir: $flNm\n"; } else { print "neither file nor dir: $flNm\n"; } }

Section 2: From a terminal window =========================================================

gfrmDev$ cd DBexportFiles gfrmDev$ ls -l total 1536 -rw-r--r-- 1 andynic staff 66192 17 Feb 17:43 export_of_gfrm_20110217_ +174314.zip -rw-r--r-- 1 andynic staff 66192 17 Feb 17:51 export_of_gfrm_20110217_ +175005.zip -rw-r--r-- 1 andynic staff 66193 17 Feb 18:30 export_of_gfrm_20110217_ +183048.zip -rw-r--r-- 1 andynic staff 66193 17 Feb 22:08 export_of_gfrm_20110217_ +220832.zip -rw-r--r-- 1 andynic staff 505830 17 Feb 20:27 importLogOf_export_of_g +frm_20110217_183048.log drwxr-xr-x 7 andynic staff 238 18 Feb 12:52 xxxx

Section 3: The code output; ========================================================= (I would have expected 5 files (*.zip, and *.log) and 3 directories (., .., xxxx), but instead:

gfrmDev$ perl -w x.pl is a dir: . is a dir: .. is a file: .DS_Store neither file nor dir: export_of_gfrm_20110217_174314.zip neither file nor dir: export_of_gfrm_20110217_175005.zip neither file nor dir: export_of_gfrm_20110217_183048.zip neither file nor dir: export_of_gfrm_20110217_220832.zip neither file nor dir: importLogOf_export_of_gfrm_20110217_183048.log neither file nor dir: xxxx

Am I doing something weird that I don't see?

perl version 5.10

Mac OS X 10.6

Thanks,

Andynic

Replies are listed 'Best First'.
Re: Perl file operators seem to behave strangely
by toolic (Bishop) on Feb 18, 2011 at 13:41 UTC
    readdir
    If you're planning to filetest the return values out of a "readdir", you'd better prepend the directory in question. Otherwise, because we didn't "chdir" there, it would have been testing the wrong file.
Re: Perl file operators seem to behave strangely
by Eliya (Vicar) on Feb 18, 2011 at 13:42 UTC

    When operations on files without absolute paths behave strangely, the first thing to check is always whether your current working directory is where you think it is.

    In your case, my guess would be that it's not $GCdfltDBexpPrmPthNm, from where you're reading the file list.

Re: Perl file operators seem to behave strangely
by locked_user sundialsvc4 (Abbot) on Feb 18, 2011 at 14:43 UTC

    It would be immensely easier to read this posting if you could put it within <code> tags.   (See: Markup in the Monastery.)