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

Dear all Mighty Monks,
Is that any script reference that can check whether a file exist in a folder. Then if the file is not exist it will return something. So that I will know the files is not there. Because the way I code it is very back and slow some more got bugs. For a beginner like me in perl need to learn lot now.
Thank you.
  • Comment on Is any any script checking File Existance

Replies are listed 'Best First'.
Re: Is any any script checking File Existance
by rob_au (Abbot) on Oct 11, 2002 at 04:08 UTC
    The previous posts have pointed you in the right direction with regard to your question and file test operators. I would only add some additional information about a lesser known module included with the core Perl distribution which may also be of use if testing for the existence of a large number of files.

    The File::CheckTree module can be used to perform file tests on a large number of files within a directory tree. For example, from the documentation for this module:

    use File::CheckTree; $warnings += validate( q{ /vmunix -e || die /boot -e || die /bin cd csh -ex csh !-ug sh -ex sh !-ug /usr -d || warn "What happened to $file?\n" });

    The real power of this module however lies in the ability to perform a great number of file tests, moreso than existence (-e) checks, on a large group of files as the example above demonstrates.

     

    perl -e 'print+unpack("N",pack("B32","00000000000000000000000111001110")),"\n"'

Re: Is any any script checking File Existance
by Enlil (Parson) on Oct 11, 2002 at 03:19 UTC
    Try this:
    my $file_name = "some_file_name"; if ( -e $file_name ) { DO_STUFF }
    the -e checks for the existance of a file and returns true or false so if it does not exist it will not go into the if loop. I think this is what you are asking.

    _Enlil_

Re: Is any any script checking File Existance
by tadman (Prior) on Oct 11, 2002 at 06:19 UTC
    There is a section in perlfunc that explains the file test functions:
    -e File exists. -z File has zero size (is empty). -s File has nonzero size (returns size in bytes). -f File is a plain file. -d File is a directory. -T File is an ASCII text file. -B File is a "binary" file (opposite of -T).
    You can use any of these to test for the presence of a file, depending on your exact requirements. For example:
    if (-f $my_file) { print "Thanks for not deleting my config file $my_file\n"; } if (-B $my_file || -z $my_file) { print "I'll bet you think you're funny.\n"; }
    They look odd, I know, functions that start with dashes are a teeny bit unusual, but then again, regular expressions are far stranger.

Re: Is any any script checking File Existance
by rbc (Curate) on Oct 11, 2002 at 03:32 UTC
    you can also read about a bunch of "file test" stuff by doing ...
    $ perldoc -f-e