in reply to 'open for read' fails as "no such file or directory" but file is there

You can try to see exactly what file perl tries to open and print it in the error message by doing the interpolation in a temporary variable:

my $file = '/Users/athina/check-ma/$ID${l}/F${j}\/gangle-dihedrals-${i +}${id}${k}.xvg'; open $input, '<', $file or die "Can't open file $file: $!";
Once this is done, you can replace the single quotes by double quotes, as strings in single quotes are used literally and no interpolation happens (perl doesn't replace the variables by their value).

The variable with the file name is a good habit to have, so that you can have the exact same string used by open and printed in the error without having to assume that you and perl are looking at the same file.

  • Comment on Re: 'open for read' fails as "no such file or directory" but file is there
  • Download Code

Replies are listed 'Best First'.
Re^2: 'open for read' fails as "no such file or directory" but file is there
by fasoli (Beadle) on Nov 02, 2016 at 13:00 UTC

    This was the message I got when tried the variable with the file name.

    Can't open file /Users/athina/check-ma/$ID${l}/F${j}\/gangle-dihedrals-${i}${id}${k}.xvg: No such file or directory at auto-dash.pl line 33.

    The problem was the single quotes, once I replaced them with double quotes the problem was solved. Phew, that was a super easy one that I didn't even think to do... :( Thank you for your time and advice!

      Here's a suggestion for future development -- instead of creating the filename to be opened just in the open statement, create it ahead of time:

      my $filename = # complicated work that builds filename open ( my $fh, '<', $filename ) or die "Unable to open $filename for read: $!"; # ... close ( $fh );
      You may hear about using autodie instead, but I like writing out the open statement and the die statement, as it gives the debugger me more information from the developer me. In this case, if it fails, you can immediately copy and paste the filename into an ls command and check to see if Perl can't find the file .. or if developer me is an idiot. :)

      Alex / talexb / Toronto

      Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

        G'day Alex,

        Hand-crafting your own die messages can provide a lot more information than that provided by autodie. In some cases, using die instead of autodie is entirely appropriate. However,

        ... or die "Unable to open $filename for read: $!";

        provides no more information than

        $ perl -e 'use autodie; open $fh, "<", "not_a_file"' Can't open 'not_a_file' for reading: 'No such file or directory' at -e + line 1

        See my reply to the OP for more on this.

        — Ken