Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find a user's home directory in Perl?

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?

like image 227
Haiyuan Zhang Avatar asked Sep 25 '09 03:09

Haiyuan Zhang


People also ask

How do I find my home directory in Perl?

use File::chdir; { local $CWD = home; if (-e $file) { ... } } , platform independent, block local working directory management!

Where can I find home directory?

Starting with Windows Vista, the Windows home directory is \user\username. In prior Windows versions, it was \Documents and Settings\username. In the Mac, the home directory is /users/username, and in most Linux/Unix systems, it is /home/username.

What is the home directory of your user?

A home directory is the directory or folder commonly given to a user on a network or Unix or Linux variant operating system. With the home directory the user can store all their personal information, files, login scripts, and user information.

How do I list a directory in Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir: opendir my $dir, "/some/path" or die "Cannot open directory: $!"; my @files = readdir $dir; closedir $dir; You can also use: my @files = glob( $dir .


1 Answers

~ is a bash-ism rather than a perl-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 $HOME environment variable, such as:

if ( -e $ENV{"HOME"} . "/foo.txt" ) {     print "yes ,it exists!" ; } 

And yes, I know the user can change their $HOME environment 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:

use File::HomeDir; $fileSpec = File::HomeDir->my_home . "/foo.txt"; if ( -e $fileSpec ) {     print "Yes, it exists!\n"; } else {     print "No, it doesn't!\n"; } 

and transcript:

 pax$ touch ~/foo.txt ; perl chkfile.pl Yes, it exists!  pax$ rm -rf ~/foo.txt ; perl chkfile.pl No, it doesn't! 
like image 113
paxdiablo Avatar answered Sep 29 '22 04:09

paxdiablo