无法读取配置文件:./try.pl 第 8 行没有此类文件或目录

Couldn't read config file: No such file or directory at ./try.pl line 8

我无法读取文件的内容 tutc.txt。我想编写一个子例程来读取将从 perl 脚本调用的文件的内容。

我的模块名为Module.pm

package Module;

use warnings;
use strict;
use Carp;
use feature "switch";
no warnings 'experimental::smartmatch';

# Constructor and initialisation 
 sub new {                               #class method
    my $class = shift;              #shift without arguments is shift @_ , takes 1st element of argument array
    my $self = {@_};                #created a Hash reference with @_ helping to store values in a hash
    bless ($self, $class);          #turning self into an object by telling which class it belongs to without hardcode name in
    $self->{_created} = 1; #syntax for accessing the contemts of a hash: refrence $object_name->{property_name}.
    return $self;
  }

 #reading from config file
 sub read {
    my ($self, $file) = shift;
    my $self = @_;
    open my $config_fh, $file or return 0;
    $self->{_filename} = $file;     # Store a special property containing the name of the file

    my $section;
    my $config_name;
    my $config_val;

    while (my $line = <$config_fh>)
    {
            chomp $line;
            given ($line) {
                    when (/^\[(.*)\]/)
                            {
                            $section = ;
                            }
                    when (/^(?<key>[^=]+)=(?<value>.*)/)
                    {
                            $section //= '';
                            $self->{"$section.$config_name"} = $config_val;
                    }
            }
    }
close $config_fh;

return $self;
}

  sub fetch {
    my ($self, $key) = shift;
    return $self->{$key};
 }

我的 perl 文件如下所示:

 #!/usr/bin/perl

 use Module;
 use strict;
 use warnings;

 my $value = Module->new();
 $value->read('/Users/hhansraj/git/edgegrid-curl/tutc.txt') or die "Couldn't        read config file: $!";
 print "The author's first name is ",$value->fetch('author.firstname'),"\n";

我的文本文件如下所示: [作者] 名字=道格 姓氏=谢泼德

 [site]
 name=Perl.com
 url=http://www.perl.com/

在您的 "read" 子例程中,前两行代码(如下所列)看起来可能是问题的根源。

my ($self, $file) = shift;
my $self = @_;

在第一行中,您将删除 @_ 数组的第一个元素(子例程的参数)并将其放入 $self 变量中。 $file 变量中没有输入任何内容。在第二行中,您重新声明了 $self 变量并为其分配了 @_ 数组剩余部分的大小。我怀疑您的代码正在将 value/data 分配给您想要的 $self 变量。

由于未为 $file 变量分配任何值,这可能会导致 open 函数出现问题。此外,您在尝试打开文件时没有指定文件模式。要仅修复缺少的模式规范以指定只读模式,您可以更改以下行:

open my $config_fh, $file or return 0;

成为

open (my $config_fh, "<", $file) or return 0;