考えると入力
my %dict = (
a => ["is", "isn't"],
b => ["test", "demo"],
);
my $template = 'This [a] a [b]';
アルゴリズム::ループバージョン:
use Algorithm::Loops qw(NestedLoops);
my @loops;
for ($template) {
if (/\G \[ /xgc) {
/\G ([^\]]*) \] /xgc
or die("Missing \"]\"\n");
my $var = $1;
length($var)
or die("Empty \"[]\"\n");
$dict{$var}
or die("Unknown var \"$var\"\n");
push @loops, $dict{$var};
redo;
}
if (/\G ([^\[]+) /xgc) {
push @loops, [ $1 ];
redo;
}
/\G \z /xgc
or die("Internal error");
}
my $iter = NestedLoops(\@loops);
while (my @parts = $iter->()) {
print(join('', @parts), "\n");
}
出力:
This is a test
This is a demo
This isn't a test
This isn't a demo
glob
ベースのバージョン:エラーチェックがなければ、その特定の辞書のための
$_ = '{'.join(',', map quotemeta($_), @$_).'}'
for values(%dict);
my $glob;
for ($template) {
if (/\G \[ /xgc) {
/\G ([^\]]*) \] /xgc
or die("Missing \"]\"\n");
my $var = $1;
length($var)
or die("Empty \"[]\"\n");
$dict{$var}
or die("Unknown var \"$var\"\n");
$glob .= $dict{$var};
redo;
}
if (/\G ([^\[]+) /xgc) {
$glob .= $1;
redo;
}
/\G \z /xgc
or die("Internal error");
}
while (defined(my $string = glob($glob))) {
print($string, "\n");
}
、これはかなり縮小することができます。
$ perl -E'say for glob shift=~s/\[((a)|b)]|(.)/$3?"\Q$3":$1?"{is,isn'\''t}":"{test,demo}"/serg' \
'This [a] a [b]'
This is a test
This is a demo
This isn't a test
This isn't a demo
でしょうあなたは 'sのを/使用することを含むために受け入れソリューション\ [a \] /は '$ string'にありますか? –
それは私の元の文字列を変更するだけでしょうか。 –
あなたは "sprintf"を探しているようですが、もしあなたが "[a]"のものと結婚していなければ。 – AKHolland