我无法读取文件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 = $1;
}
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/
答案 0 :(得分:0)
在“读取”子程序中,看起来前两行代码(如下所列)可能是您问题的根源。
my ($self, $file) = shift;
my $self = @_;
在第一行中,您将删除@_数组的第一个元素(子例程的参数)并将其放入$ self变量中。并没有输入$ file变量。在第二行中,您将重新声明$ self变量,并为其分配@_数组左侧的大小。我怀疑你的代码是将值/数据分配给你想要的$ self变量。
由于$ file变量没有被赋值任何值,这可能会产生open函数的问题。此外,您在尝试打开文件时未指定文件模式。要仅修复缺少的模式规范以指定只读模式,您可以更改以下行:
open my $config_fh, $file or return 0;
是
open (my $config_fh, "<", $file) or return 0;