How can I make Perl recognize paths with '~'?

我的梦境 提交于 2019-12-05 08:25:44

For a reliable (and easy) cross-platform method, try File::HomeDir:

use File::HomeDir;
print File::HomeDir->my_home;

You can pass the path to glob to get it expanded.

The glob function understands standard Unix file globbing.

my $file = glob('~/Documents/file.txt');

From Bruno's comment, you could do it this way:

$path =~ s/^~(\w*)/ ( getpwnam( $1 || $ENV{USER} ))[7] /e;

The e flag replaces the expression with the result of executing or evaluating the replace expression.

tchrist

Use angle-quotes, not double-quotes:

open(my $fh, "< :crlf :encoding(cp1252)",
              <~/Documents/file.txt>)
    || die "couldn't open Winblose text file ~/Documents/file.txt: $!";

The <xxx> iteration operator, which people usually think of as syntactic sugar for the readline function, instead calls the glob function if there are shell metachars in xxx, and tilde count as one of those.

You might prefer an open mode of <:encoding(Latin1). It just depends on the file.

Try to replace ~ with $ENV{HOME}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!