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
~
~/blahIf 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; Section 9.6
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access