home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePerl CookbookSearch this book

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 Filenames Perl Cookbook Next: 7.4. Making Perl Report Filenames in Errors
7.2. Opening Files with Unusual Filenames Book Index 7.4. Making Perl Report Filenames in Errors

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.