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

Perl Monks,

I am processing and combining the contents of several files, one of which is (appropriately) not always created. If it exists, I need to open it. Otherwise, the program must go on.

Thanks.

Replies are listed 'Best First'.
Re: Opening a File If It Exists
by The Mad Hatter (Priest) on Jul 21, 2004 at 17:15 UTC
    Test for existance using the -e operator. See perldoc -f -X for more info. For example:
    if (-e "some_file") { # do your thing }
Re: Opening a File If It Exists
by Eimi Metamorphoumai (Deacon) on Jul 21, 2004 at 17:44 UTC
    You could use something like
    if (open COULDBE, "filename"){ #process here close COULDBE; }
    which will silently continue if the file can't be opened for whatever reason (doesn't exist, permissions, etc).
Re: Opening a File If It Exists
by grinder (Bishop) on Jul 21, 2004 at 17:45 UTC
    If it exists, I need to open it.

    Just try and open it. The world won't come to an end if you try to open a file that doesn't exist, just trap the error.

    if( open( IN, '<', $somefile ) ) { # it's there, do something with it close(IN); } else { warn "wasn't able to open $somefile (reason=$!)\n"; }

    You might also want to consider using IO::File objects, which lend themselves to being passed to subroutines. Of course you can also pass typeglobs around, e.g.

    process(*IN); sub process { *FH = shift; while( <FH> ) { .... } }

    I do it all the time, but it is considered antiquated in some circles, as it's a throwback to the Perl 4 era.

    - another intruder with the mooring of the heat of the Perl

      You might also want to consider using IO::File objects ... you can also pass typeglobs

      Or you can use lexical, autovivified filehandles. These are the variety I prefer:

      open my $in, "<", $filename or die "open $filename: $!"; process($in); close $in;