gpt4 book ai didi

perl - 如何减少常量中的重复?

转载 作者:行者123 更新时间:2023-12-04 13:07:52 25 4
gpt4 key购买 nike

我有这个 Perl 脚本,其中包含许多已定义的配置文件常量。例如:

use constant  {
LOG_DIR => "/var/log/",
LOG_FILENAME => "/var/log/file1.log",
LOG4PERL_CONF_FILE => "/etc/app1/log4perl.conf",
CONF_FILE1 => "/etc/app1/config1.xml",
CONF_FILE2 => "/etc/app1/config2.xml",
CONF_FILE3 => "/etc/app1/config3.xml",
CONF_FILE4 => "/etc/app1/config4.xml",
CONF_FILE5 => "/etc/app1/config5.xml",
};

我想减少 "/etc/app1"和 "/var/log"的重复,但使用变量不起作用。同样,使用先前定义的常量在同一个“使用常量块”中也不起作用。例如:
use constant {
LOG_DIR => "/var/log/",
FILE_FILENAME => LOG_DIR . "file1.log"
};

不起作用。

使用单独的“使用常量”块可以解决这个问题,但这会增加很多不需要的代码。

这样做的正确方法是什么?

谢谢你。

最佳答案

Using separate "use constant" blocks does workaround this problem, but that adds a lot of unneeded code.



真的吗?
use constant BASE_PATH => "/etc/app1";

use constant {
LOG4PERL_CONF_FILE => BASE_PATH . "/log4perl.conf",
CONF_FILE1 => BASE_PATH . "/config1.xml",
CONF_FILE2 => BASE_PATH . "/config2.xml",
CONF_FILE3 => BASE_PATH . "/config3.xml",
CONF_FILE4 => BASE_PATH . "/config4.xml",
CONF_FILE5 => BASE_PATH . "/config5.xml",
};

我不认为这有很多问题。您仅在一处指定了基本路径,从而遵守 DRY 原则。如果您使用环境变量分配 BASE_PATH:
use constant BASE_PATH => $ENV{MY_BASE_PATH} || "/etc/app1";

...然后,您可以通过一种廉价的方式重新配置常量,而无需编辑代码。这有什么不喜欢的?

如果您真的想减少重复的“BASE_PATH .”连接,您可以添加一些机器来自己安装常量并将其分解:
use strict;
use warnings;

use constant BASE_PATH => $ENV{MY_PATH} || '/etc/apps';

BEGIN {
my %conf = (
FILE1 => "/config1.xml",
FILE2 => "/config2.xml",
);

for my $constant (keys %conf) {
no strict 'refs';
*{__PACKAGE__ . "::CONF_$constant"}
= sub () {BASE_PATH . "$conf{$constant}"};
}
}

print "Config is ", CONF_FILE1, ".\n";

但在这一点上,我认为平衡已经从正确转向讨厌 :) 首先,您不能再 grep 为 CONF_FILE1 并查看它的定义位置。

关于perl - 如何减少常量中的重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/228978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com