[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Sheflug] Slightly OT :perl file exists test



>>>>> "Seb" == Seb James <seb [at] hypercubesystems.co.uk> writes:

    Seb> On Wed, 2004-05-12 at 11:44, Chris Johnson wrote:
    >> Can anyone provide me with a couple of lines of perl to test
    >> whether a file exists or not please.  I think I could work it
    >> by doing an "open or die" but I seem to remember this wasn't a
    >> very efficient way of doing it.  I'm editing the cgi scripts
    >> for Dansguardian on IPCop so that links to edit the "included"
    >> files are presented at the bottom of each "edit file" page.

    Seb> Have a look at the documentation at www.perl.org regarding
    Seb> file opening and closing. The return values from these
    Seb> functions will do what you want.


For all of the file tests, run "perldoc -f -X"

Attempting to open a file to check if it exists sounds like a really
bad idea - if you need to get a filehandle to a file, use
open(). Otherwise, just use one (or more) of the tests.

There are a large number of reasons an open() could fail - just
die()ing because you can't find a file is silly. On the other hand, if
you've checked the file is there but the open fails, that is more
likely to be worthy of a die().

Try something along the lines of:

  #!/usr/bin/perl

  use strict;
  use warnings;

  my $file = shift || die "No file specified! Stopping";

  if ( -f $file ) {
    open FH, "<", $file or die "Can't open file $file: $!";

    # process file

    close FH or die "Problems closing file $file: $!";
  }


Just throw that into a file and call with the name of the file as an
argument.

Cheers,

Baz.

-- 
Barrie J. Bremner
baz-sheflug [at] barriebremner.com      http://barriebremner.com/


___________________________________________________________________

Sheffield Linux User's Group -
http://www.sheflug.co.uk/mailfaq.html

  GNU the choice of a complete generation.