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

Hi! I'm using some software within my perl script and need to identify whether in the input file is empty or not before the processing starts. What I've written below isn't working. Is there an easier way to do this than calling the system? I tried opening the file and looking at the first line, but the while loop interferes with my logic.

#!/usr/bin/perl5.8.8 use strict; use warnings; my $cmd = "-s /home/vcg/Documents/Trial/temp"; if (system($cmd) == 0) { print "File exists!"; } else { print "File does NOT exist!";}

Forever Thanks!

Replies are listed 'Best First'.
Re: Check for an empty file
by ikegami (Patriarch) on Sep 22, 2011 at 18:56 UTC

    You could use Perl's -s instead of the shell's.

    if (-s "/home/vcg/Documents/Trial/temp")

    Note that empty (-z or !-s) and non-existent (!-e) are different things.

      Thanks! It's working great! I'd prefer not to use the shell if I can help it!
      I had some trouble with this a while back. -s returns a zero if the file is either zero bytes or nonexistent. It got a bit confusing until I worked out what was happening.

        Actually, it returns undef (and sets $!) if the file is non-existent.

Re: Check for an empty file
by roboticus (Chancellor) on Sep 22, 2011 at 18:55 UTC

    Jeri:

    if ( -z '/home/vcg/Documents/Trial/temp' ) { print "File is empty!\n"; }

    See perlfunc for the other -X file/dir checking functions.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

    Update: Added link to perlfunc.