I need to check whether a file in a user’s home directory exists so use file check:
if ( -e "~/foo.txt" ) {
print "yes, it exists!" ;
}
Even though there is a file called foo.txt under the user’s home directory, Perl always
complains that there is no such file or directory. When I replace “~” with /home/jimmy (let’s say the user is jimmy) then Perl give the right verdict.
Could you explain why “~” dosen’t work in Perl and tell me what is Perl’s way to
find a user’s home directory?
~is abash-ism rather than aperl-ism, which is why it’s not working. Given that you seem to be on a UNIX-type system, probably the easiest solution is to use the$HOMEenvironment variable, such as:And yes, I know the user can change their
$HOMEenvironment variable but then I would assume they know what they’re doing. If not, they deserve everything they get 🙂If you want to do it the right way, you can look into File::HomeDir, which is a lot more platform-savvy. You can see it in action in the following script
chkfile.pl:and transcript: