develooper Front page | perl.beginners | Postings from May 2007

Re: Inconsistent results from file test (-X) operators

Thread Previous | Thread Next
From:
John W. Krahn
Date:
May 16, 2007 18:52
Subject:
Re: Inconsistent results from file test (-X) operators
Message ID:
464BB54C.6070906@telus.net
R (Chandra) Chandrasekhar wrote:
> Dear Folks,

Hello,

> I have encountered inconsistent behaviour with the file test (-X)
> operators. I am using perl, v5.8.8 built for i486-linux-gnu-thread-multi
> on a Kubuntu Feisty system.
> 
> I show below my minimal test file:
> 
> ----------- Minimal Test File -----------
> #!/usr/bin/perl -w

use strict;

> use diagnostics;
> 
> # Minimal example for problem with file test, or -X, operators
> 
> $testdir = "/usr";
> 
> opendir(DH, $testdir) or die "Could not open $testdir: $!\n";
> 
> while (defined($file = readdir(DH)))
>     {
>     if (-d $file)

perldoc -f readdir
    readdir DIRHANDLE
            Returns the next directory entry for a directory opened by
            "opendir".  If used in list context, returns all the rest of the
            entries in the directory.  If there are no more entries, returns
            an undefined value in scalar context or a null list in list
            context.

            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.

                opendir(DIR, $some_dir) || die "can’t opendir $some_dir: $!";
                @dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
                closedir DIR;


So:

    if (-d "$testdir/$file")


>         {
>         print "$file is a directory\n";
>         }
>     elsif (-f $file)

And:

    elsif (-f "$testdir/$file")

Or more simply:

    elsif (-f _)


>         {
>         print "$file is a regular file\n";
>         }
>     else
>         {
>         print "$file is neither a directory nor a regular file\n";
>         }
>    }
> 
> closedir(DH);



John
-- 
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order.       -- Larry Wall

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About