Perl Cookbook

Perl CookbookSearch this book
Previous: 7.2. Opening Files with Unusual FilenamesChapter 7
File Access
Next: 7.4. Making Perl Report Filenames in Errors
 

7.3. Expanding Tildes in Filenames

Problem

You want to open filenames like ~username/blah, but open doesn't interpret the tilde to mean a home directory.

Solution

Expand the filename manually with a substitution:

$filename =~ s{ ^ ~ ( [^/]* ) }
              { $1
                    ? (getpwnam($1))[7]
                    : ( $ENV{HOME} || $ENV{LOGDIR}
                         || (getpwuid($>))[7]
                       )
}ex;

Discussion

The uses of tilde that we want to catch are:

    ~user
    ~user/blah
    ~
    ~/blah

If no name follows the ~, the current user's home directory is used.

This substitution uses /e to evaluate the replacement as Perl code. If a username follows the tilde, it's stored in $1, which getpwnam uses to extract the user's home directory out of the return list. This directory becomes the replacement string. If the tilde was not followed by a username, substitute in either the current HOME environment variable or the LOGDIR one. If neither of those environment variables is valid, look up the effective user ID's home directory.

See Also

Your system's getpwnam (2) manpage; the getpwnam function in perlfunc (1) and Chapter 3 of Programming Perl; Recipe 9.6


Previous: 7.2. Opening Files with Unusual FilenamesPerl CookbookNext: 7.4. Making Perl Report Filenames in Errors
7.2. Opening Files with Unusual FilenamesBook Index7.4. Making Perl Report Filenames in Errors