in reply to Opening a File If It Exists

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

Replies are listed 'Best First'.
Re^2: Opening a File If It Exists
by revdiablo (Prior) on Jul 21, 2004 at 18:50 UTC
    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;