Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: How to convert unix ~path (tilde) to full path

by jwest (Friar)
on Apr 05, 2002 at 17:01 UTC ( #156987=note: print w/replies, xml ) Need Help??

in reply to How to convert unix ~path (tilde) to full path

The 'HOME' environment variable is set to the home directory of the user, so:
use File::Spec; my $FileName; my $homedir = $ENV{HOME}; if ($FileName =~ /^~/) { $FileName =~ s/^~//; $FileName = File::Spec->catfile($homedir, $FileName); }
would probably do the trick.

-><- -><- -><- -><- -><-
All things are Perfect
    To every last Flaw
    And bound in accord
         With Eris's Law
 - HBT; The Book of Advice, 1:7

Replies are listed 'Best First'.
Re: Re: How to convert unix ~path (tilde) to full path
by Kanji (Parson) on Apr 05, 2002 at 17:22 UTC

    It's a little redundant to see if the string begins with a ~ and then remove it, when s/^~// will only return true if it replaced anything.

    Also, it might be nice to fallback to the home directory returned by getpwuid just in case $ENV{'HOME'} isn't set ...

    use File::Spec; my $filename = '~/public_html/'; if ( $filename =~ s<^~([^/]*)/></> ) { my $homedir = $1 ? (getpwnam($1))[7] # specified user : $ENV{'HOME'} || (getpwuid($<))[7] # ourselves or die "Where's your home?\n"; $filename = File::Spec->catfile($homedir, $filename); }

    Update: Fixed to account for jeffenstein's observation.


Re: Re: How to convert unix ~path (tilde) to full path
by jeffenstein (Monk) on Apr 05, 2002 at 17:27 UTC

    Unfortunately, that only works for ~/path. The ~ form also works as ~user2, meaning the home directory of user2, not the current user's home directory.

    Something more complete might look like this: Warning: untested code

    my $filename = "~user2/tmp"; if( $filename =~ m@^\~([^/])+@){ my $home = (getpwnam($1))[7]; if( $home){ $filename =~ s@^\~[^/]+@$home@; } }else{ $filename =~ s@^\~@$ENV{'HOME'}@; }

    This should handle both cases.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://156987]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (1)
As of 2018-02-23 05:30 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (300 votes). Check out past polls.