Search code examples
perlfileperl-module

Not able to open a file to read since file name starts with 'r'


My file's name is "rootpass" and I am trying to read it like this,

my $rootpass;
my $passfile = "$jobDir/\rootpass";
print "file name = $passfile\n";
if( -e $passfile)
{    
    open ROOTPASS, '$passfile';
    $rootpass = <ROOTPASS>;
    print "$rootpass\n";
}
else
{
    print "No read permissions on password file $passfile\n";
    exit 1;
}

I get an error like this,

Unsuccessful stat on filename containing newline at ReadFile.pl line 106. 

106 is the if() line. I have tried the following,

  1. made it my $passfile = "$jobDir\/rootpass"; to escape the escape char
  2. made it my $passfile = "$jobDir//rootpass"; to escape the 'r' so it wont think I have a return char in the file name

How do I read the file whose name is rootpass under the directory name contained in the variable $jobDir?


Solution

  • This line

    my $passfile = "$jobDir/\rootpass";
    

    will put a carriage-return character—hex 0D—where \r is in the string. You presumable mean just

    my $passfile = "$jobDir/rootpass";
    

    The line

    open ROOTPASS, '$passfile';
    

    will try to open a file called—literally—$passfile. You want

    open ROOTPASS, $passfile;
    

    or, much better

    open my $pass_fh, '<', $passfile or die $!;
    

    Here's a summary

    use strict;
    use warnings;
    
    my $jobdir   = '/path/to/jobdir';
    my $passfile = "$jobdir/rootpass";
    
    print "file name = $passfile\n";
    
    open my $pass_fh, '<', $passfile or die qq{Failed to open "$passfile" for input: $!};
    my $rootpass = <$pass_fh>;
    print "$rootpass\n";
    

    output

    file name = /path/to/jobdir/rootpass
    Failed to open "/path/to/jobdir/rootpass" for input: No such file or directory at E:\Perl\source\rootpass.pl line 9.