Is there any way to check whether a file is an empty file using PERL program?

Viewed 5554

I am looking a small script which will tell me whether a file is an empty file or not , but i am unable to display this.

I have used the below code :

opendir DIR,$directory ;
while (my $dir =readdir DIR) {
    if (-s "$dir") {
    print "This is an empty file";
    }
}

Here i am unable to print "This is an empty file" and my code does not went inside the if loop. Can anyone tell me what is the wrong in the above code

2 Answers

The relevant file test operators are:

  • -z: check if the file is empty.
  • -s: check if the file has nonzero size (returns size in bytes).

You are checking if $dir is non-empty, so opposite of what you are trying to achieve. Use -z (or !-s) instead.

Also, each $dir is just the filename without the path, so you need to include it yourself if you aren't processing the current directory.

if (-z "$directory/$dir") {
    print "This is an empty file";
}

Your main problem is that readdir() doesn't return what you think it does. It returns the names of the files in the directory. But the names you get back don't have the directory path attached. And the -s operator needs the full path to the file in order to find it.

So you need to attach the directory name yourself. Something like this will work:

opendir DIR, $directory ;
while (my $dir = readdir DIR) {
    # Note: Full path here.
    if (-s "$directory/$dir") {
        print "This is an empty file";
    } 
}

But there are a couple of other things I'll fix. Firstly -s returns the size of the file. So that's true for a non-empty file. Which means that your logic is reversed. It actually needs to be this:

if (-s "$directory/$dir") {
    print "This is a non-empty file";
} else {
    print "This is an empty file";
}

It's also worth noting that using bareword directory handles isn't a very good idea. It's far better to use lexical variables as handles. I'd write your code like this:

opendir my $dir_h, $directory ;
while (my $file = readdir $dir_h) {
    # Note: Full path here.
    if (-s "$directory/$file") {
        print "This is a non-empty file";
    } else {
        print "This is an empty file";
    } 
}

Oh, I also sneakily changed a variable name. $file seems a far better name thant $dir :-)

Related