Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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.
--jwest


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


Comment on Re: How to convert unix ~path (tilde) to full path
Download Code
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.

        --k.


    :
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://156987]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (15)
As of 2015-07-01 19:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (19 votes), past polls