返回 perl 中变量和字符串的组合



我有一个从配置文件读取的模块。它将配置文件中的值提取并存储到$path、$file$host中。当我将这些值传递到一个新的子例程中并与字符串连接并尝试返回它时,它失败了。给我一个错误:

模块:

package Module;
use strict;
use Carp;
# 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) = @_;
    my ($line, $section);
    open(HFILE, "$file") || die "Could not open file '$file' $!";
    $self->{_filename} = $file;     # Store a special property containing the name of the file
    while (chomp (my $line = <HFILE>))
    {
            if ($line =~ /^[(.*)]/)
            {
                    $section = $1;
            }
            elsif ($line =~ /^([^=]+)=(.*)/)
            {
                    my ($config_name, $config_val) = ($1, $2);
                    if ($section)
                            {
                                    $self->{"$section.$config_name"} = $config_val;
                            } else {
                                    $self->{$config_name} = $config_val;
                                    }
            }
    }
    close HFILE;
    return 1;
    }

#fetching values needed
sub fetch {
    my ($self, $key) = @_;
    return $self->{$key};
}
sub _setup{
    my ($self, @location) = @_;
    my $command = ''.$location[1].' --eg-config '.$location[0].' -H "Host:'.$location[2].'" -ik https://'.$location[2].'';
    return $self->$command;
}

脚本:

#!/usr/bin/perl
use Module;
use strict;
my $value = Module->new();
$value->read("/Users/hhansraj/git/edgegrid-curl/api.txt") or die "Couldn't read config file: $!";
my $path=$value->fetch('location.path');
my $file=$value->fetch('location.file');
my $host=$value->fetch('credentials.host');
$value->_setup($path,$file,$host);

由于您正在读取INI文件,我强烈建议使用配置模块,例如:Config::ZOMG 或 Config::INI

后者应该很简单:

my $config = Config::INI::Reader->read_file('config.ini');
print $config->{location}->{file};

使用像Moo这样的适当对象,您的代码将是:

MyClass.pm:

package MyClass;
use Config::INI::Reader;
use Moo;
has 'config_file' => (is => 'ro',   required => 1);
has 'config'      => (is => 'lazy', default => sub { Config::INI::Reader->read_file(shift->config_file); });
sub setup {
    my ($self) = @_;
    my $path = $self->config->{location}->{path};
    my $file = $self->config->{location}->{file};
    my $host = $self->config->{credentials}->{host};
    return sprintf "%s --eg-config '%s' -H 'Host: %s' -ik https://%s", ($file, $path, $host, $host); 
}

脚本:

use MyClass;
my $mc = MyClass->new( config_file => 'config.ini');
$mc->setup();

无论如何,文件的实际问题是您正在尝试在以$command的内容命名$self上调用方法。也许您只想在 _setup 方法中返回 $command 变量?

我怀疑您希望_setup方法实际执行命令。 你最好的选择是system()。 要使用"system",您需要检查返回值是否为 0。 从之前链接的文档:

Since "SIGINT" and "SIGQUIT" are ignored during the execution
of "system", if you expect your program to terminate on receipt
of these signals you will need to arrange to do so yourself
based on the return value.
   @args = ("command", "arg1", "arg2");
   system(@args) == 0
       or die "system @args failed: $?"

不过,在执行此操作之前,我强烈建议您先将其打印为标准输出,以验证最终命令字符串是否完全符合您的要求。 由于这是配置/设置模块的一部分,因此您也可以添加另一个称为"测试"或类似内容的配置选项。 然后,当调用 _setup() 时,它可以打印命令或根据 "testing" 的值执行它。

如果返回值不为零,则出了点问题,您还不如在那里 die()。 但是,一旦您解决了错误并使其运行,命令失败通常是由模块用户提供的不良配置值引起的 - 因此,您应该使用 Carp 模块中的 croak()(我注意到您已经在使用模块)。 这将从调用方的角度而不是模块的角度突出显示失败。

把这个长羽毛放进去,我们得到的东西是这样的:

    ... as above ...
    bless ($self, $class);       #turning self into an object by telling which ...
    $self->{_created} = 1;       #syntax for accessing the contemts of a hash: ...
    $self->{_testing} = 0        # Initialize new config option
    return $self;
}
... etc ...
sub _setup{
    my ($self, @location) = @_;
    my $command = sprintf("%s --eg-config '%s' -H 'Host: %s' -ik https://%s",
                          @location[1,0,2,2]);
    if $self->_testing {
        print "Would have executed: $commandn"
    }
    else {
        system($command) == 0 or croak "system $command failed: $?"
    }
}

最新更新