如何打开一个包含特殊字符的文件,例如$?

问题描述 投票:-2回答:2

看起来相当简单,但名称中的“$”会导致名称分裂。我尝试将字符转出,但当我尝试打开文件时,我得到了GLOB()。

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

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

perl special-characters
2个回答
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
投票

考虑使用CPAN模块File::SlurperPath::Tiny,它将处理使用open和readline,检查错误和编码的确切细节(如果适用)(大多数文本文件编码为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

© www.soinside.com 2019 - 2024. All rights reserved.