in reply to how to prevent open from dying

if, warn and next

while (...) { local *INFILE; if (!open(INFILE, '<', $inputFile)) { warn("Unable to open analysis file $inputFile: $!\n"); next; # } ... }

Replies are listed 'Best First'.
Re^2: how to prevent open from dying
by derby (Abbot) on Jun 30, 2006 at 16:08 UTC

    Don't forget to limit the scope of your file handles .. or just use lexicals:

    while ( ... ) { open my $fh, '<', $inputFile or warn( "Unable to open analysis file $inputFile: $!\n" ); next unless defined $fh ... }

    -derby
      I hate testing for the same condition twice in a row, as you did.
      while ( ... ) { my $fh; if (!open($fh, '<', $inputFile)) { warn( "Unable to open analysis file $inputFile: $!\n" ); next; } ... }
Re^2: how to prevent open from dying
by duff (Parson) on Jun 30, 2006 at 16:07 UTC

    Why not use lexical filehandles too? :-)

Re^2: how to prevent open from dying
by coontie (Sexton) on Jun 30, 2006 at 15:44 UTC
    - yes, I'll use $! instead
    - can you explain the "3arg" deal? So nothing can be slipped in the file name? Like "; cat /etc/passwd" or smth?
    - what's the point of limiting file handles??
    Anyway, thank you all for your replies.

      The open with 3 args seperate special characters from the filename, allowing you to access files you couldn't access before, and preventing the unintended creation, destruction and execution of other files.

      Limiting the scope of all variables (not just file handles) is a great practice. It frees resources earlier. It limits the number of things the programmer and the maintainer must track. It prevents bugs and the maintainability nightmares of having a variable server multiple purposes. etc.