我有这样的字符串:
constant = 0.015
history = 90
[thresholds]
up = 100
down = -100
persistence = 0
[thresholds]
up = 100
down = -100
persistence = 0
我必须将其转换为这样的格式:
config.n8_v2_BB_RSI_SL = {
constant: 0.015,
history: 90,
thresholds: {
up: 100,
down: -100,
persistence: 0 },
thresholds: {
up: 100,
down: -100,
persistence: 0 }
};
我在第一次[阈值]中没有关闭括号。我不知道这是怎么回事。 我的工作:
$a =~ s/(?<!\])(?=[\n])/,/g;
$a =~ s/ =/:/g;
$a =~ s/(?<![\D\d])/config.n8_v2_BB_RSI_SL = {\n/g;
$a =~ s/\[//g;
$a =~ s/\]/: {/g;
if ($a =~ /: \{/) {
$a =~ s/(?![\n\D\d])/ \}/g;
}
$a =~ s/(?![\n\D\d])/\n\};/g;
print "$a \n";
config.n8_v2_BB_RSI_SL = {
constant: 0.015,
history: 90,
thresholds: {
up: 100,
down: -100,
persistence: 0,
thresholds: {
up: 100,
down: -100,
persistence: 0 }
};
persistence: 0
之后我必须添加},
。怎么样? [thresholds]可能会出现1次以上,或者永远不会出现。
答案 0 :(得分:1)
SELECT
答案 1 :(得分:0)
您可以use Config::IniFiles
读取输入,use JSON
来生成输出。 (这是JSON吗?)
或者...
使用一袋肮脏的技巧,这个:
my $s=join"",<DATA>;
my $n='00000001';
$s=~s/^(.*?)(\w+)/$1_@{[$n++]}_$2/gm;
$s=sz({conf($s)});
$s=~s,\b_(\d{8})_(\w+),$2,g;
print "config.n8_v2_BB_RSI_SL = $s;\n";
sub sz {my$c=shift;ref$c?"{\n".(join",\n",map{"$_: ".sz($$c{$_})}sort keys%$c)."}":$c}
sub conf{
my($hr,$section)=({});
my@r=(qr/^\s*\[\s*(.*?)\s*\]/,
qr/^\s*([^\:\=]+?)\s*[:=]\s*(.*?)\s*$/);
/$r[0]/ and $$hr{$section=$1}||={} or
/$r[1]/ and defined$section?$$hr{$section}{$1}:$$hr{$1}=$2
for split"\n",shift;
%$hr;
}
__DATA__
constant = 0.015
history = 90
[thresholds]
up = 100
down = -100
persistence = 0
[thresholds]
up = 20
down = -100
persistence = 0
[peaks]
up = 100
down = -100
persistence = 0
产生这个:
config.n8_v2_BB_RSI_SL = {
constant: 0.015,
history: 90,
thresholds: {
up: 100,
down: -100,
persistence: 0},
thresholds: {
up: 20,
down: -100,
persistence: 0},
peaks: {
up: 100,
down: -100,
persistence: 0}};