【问题标题】:How to read files in a directory, open it and get the words for each line in perl?如何读取目录中的文件,打开它并获取 perl 中每一行的单词?
【发布时间】:2011-05-31 02:44:15
【问题描述】:

我正在尝试编写一个 perl 脚本,首先它会打开一个目录(目录中有多个文件),其次它会读取目录中的文件 strong>,然后将单词逐行放入数组中,并将这些单词作为参数发送到 c++ 程序。 我尝试编写脚本,但处理文件时出现问题,它打开目录但我无法访问文件,

这类问题应该有不止一个答案,我的脚本是:

my $directory = '.';
my @connection;
opendir (DIR, $directory) or die $!;

    while (my $file = readdir(DIR)) {
            next if ($file =~ m/^\./);
            print "$file\n";
            open (MYFILE, '$file') or die $!;# error is in here, can not open/
            while (<MYFILE>)
            {
            # split each input line; words are separated by whitespace
                    for $word (split)
                    {
                            #put the words in an array
                            #no need to store words, can be overwritten in array
                            #system() for calling c++ code
                    }
            }
    }

【问题讨论】:

    标签: string perl variables


    【解决方案1】:

    删除$file 周围的'' 引号:

    open (MYFILE, $file) or die $!;
    

    在 Perl 中,单引号将按字面意思引用字符串并且不解释任何内容。如果要解释转义字符和变量名,则需要使用双引号。但是,在这种情况下,您只有一个变量而没有其他任何东西,您根本不应该引用它,即使从技术上讲 "$file" 是正确的。

    【讨论】:

    • 我知道,但问题是我无法访问文件,打开 (MYFILE, '$file') 或死 $!;# error is in here
    • @berkay 删除 $file 周围的引号。查看更新的答案。
    猜你喜欢
    • 2011-08-02
    • 2013-06-19
    • 2021-09-14
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多