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

Hi, How does one check for existence of a file in perl, say to check for existence for a shell script before executing it from perl. also, how to check the return code from the shell script and act on it ...thx for the help
  • Comment on checking for existence of a file in perl

Replies are listed 'Best First'.
Re: checking for existence of a file in perl
by Corion (Patriarch) on Jan 13, 2009 at 20:07 UTC
Re: checking for existence of a file in perl
by toolic (Bishop) on Jan 13, 2009 at 20:09 UTC
Re: checking for existence of a file in perl
by davido (Cardinal) on Jan 13, 2009 at 22:24 UTC

    For your specific needs, checking for the existence of a file may be more work than is needed (to do well), and too unreliable. If it's an executable shell script, does it reside in the account's root directory, in a /bin folder somewhere, or in some other alternate location? If the user moves the executable and then puts a pointer in his path the shell script may remain executable, while disappearing from where your Perl script expects it to be.

    To put it in simple terms, just because the file doesn't exist where you expect it to doesn't mean it won't execute. And just because it does exist doesn't mean it will execute.

    Rather than testing for its existence, it might be better to test for success in execution. If the real question is "can I execute the script", just do it, and write some code that handles failure to execute.


    Dave

Re: checking for existence of a file in perl
by repellent (Priest) on Jan 13, 2009 at 20:13 UTC
    To perform a thorough check (for most cases):
    # make sure $path is a plain file (not a dir or other type), is readab +le, and is executable if (-f $path && -r $path && -x $path)
      Per the docs, this is better written as:
      if (-f $path && -r _ && -x _)
Re: checking for existence of a file in perl
by setebos (Beadle) on Jan 13, 2009 at 22:57 UTC
    cli: perldoc -f -e.
      also, how do i check wether the returned value is an integer or non-numeric?