How can I make Perl recognize paths with '~

2019-04-30 07:53发布

Possible Duplicate:
How do I find a user's home directory in Perl?

I'm running Ubuntu.

Whenever I pass a Perl script a path that starts with ~ (e.g. ~/Documents/file.txt) it fails finding it. I must pass the canonical path (e.g. /home/dave/Documents/file.txt).

Why is that?

Can I make Perl recognize ~ paths?

UPDATE

All the suggested solutions include changing the code in the scripts. I would like for a solution that would not involve any changes to the scripts themselves (since not all of them are mine). Perhaps something in the way Bash works?

The updated version of the question was posted at Super User.

6条回答
Emotional °昔
2楼-- · 2019-04-30 08:35

Try to replace ~ with $ENV{HOME}

查看更多
Anthone
3楼-- · 2019-04-30 08:38

The glob function understands standard Unix file globbing.

my $file = glob('~/Documents/file.txt');
查看更多
▲ chillily
4楼-- · 2019-04-30 08:44

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.

查看更多
等我变得足够好
5楼-- · 2019-04-30 08:48

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.

查看更多
我想做一个坏孩纸
6楼-- · 2019-04-30 08:51

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

查看更多
做自己的国王
7楼-- · 2019-04-30 08:53

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

use File::HomeDir;
print File::HomeDir->my_home;
查看更多
登录 后发表回答