Perl FAQ 5.18: How can I translate tildes in a filename?

Perl FAQ 5.18

How can I translate tildes in a filename?

Perl doesn't expand tildes -- the shell (ok, some shells) do. The classic request is to be able to do something like:

    open(FILE, "~/dir1/file1");
    open(FILE, "~tchrist/dir1/file1");

which doesn't work. (And you don't know it, because you did a system call without an ``|| die'' clause! :-)

If you know you're on a system with the csh, and you know that Larry hasn't internalized file globbing, then you could get away with

    $filename = <~tchrist/dir1/file1>;

but that's pretty iffy.

A better way is to do the translation yourself, as in:

    $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;

More robust and efficient versions that checked for error conditions, handed simple ~/blah notation, and cached lookups are all reasonable enhancements.


Other resources at this site: