O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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; Section 9.6

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required