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

前端 未结 5 646
借酒劲吻你
借酒劲吻你 2020-12-05 12:48

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!\" ;
}
5条回答
  •  情歌与酒
    2020-12-05 13:35

    The home directory for a user is stored in /etc/passwd. The best way to get at the information is the getpw* functions:

    #!/usr/bin/perl 
    
    use strict;
    use warnings;
    
    print "uid:", (getpwuid 501)[7], "\n",
        "name:", (getpwnam "cowens")[7], "\n";
    

    To address your specific problem, try this code:

    if ( -e (getpwuid $>)[7] . "/foo.txt" ) {
       print "yes ,it exists!";
    }
    

提交回复
热议问题