如何打开其中包含特殊字符(例如$)的文件?

时间:2019-02-14 15:00:01

标签: perl special-characters

似乎很简单,但名称中带有“ $”会导致名称拆分。我尝试转义字符,但是当我尝试打开文件时,我得到GLOB()。

my $path = 'C:\dir\name$.txt';
open my $file, '<', $path || die
print "file = $file\n";

它应该打开文件,以便我可以遍历条目。

2 个答案:

答案 0 :(得分:1)

与“ $”无关。只需遵循标准的文件处理过程即可。

use strict;
use warnings;   

my $path = 'C:\dir\name$.txt';
open my $file_handle, '<', $path or die "Can't open $path: $!";

# read and print the file line by line
while (my $line = <$file_handle>) {
    # the <> in scalar context gets one line from the file
    print $line;
}

# reset the handle
seek $file_handle, 0, 0;

# read the whole file at once, print it
{
    # enclose in a block to localize the $/ 
    #     $/ is the line separator, so when it's set to undef,
    #     it reads the whole file
    local $/ = undef;
    my $file_content = <$file_handle>;
    print $file_content;
}

答案 1 :(得分:1)

考虑使用CPAN模块File::SlurperPath::Tiny,这些模块将处理使用打开和读取行,检查错误以及在适当时进行编码的确切细节(大多数文本文件都编码为UTF-8)

use strict;
use warnings;

use File::Slurper 'read_text';
my $file_content = read_text $path;

use Path::Tiny 'path';
my $file_content = path($path)->slurp_utf8;

如果它是数据文件,请使用read_binaryslurp_raw