Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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 (Scribe) 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 romping around the Monastery: (3)
As of 2014-09-19 23:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (151 votes), past polls