You don't need to escape the } within a bracketed character class.
You do need not to accept any opening { within your bracketed character class.
use Data::Dumper;
my $string = 'some text ###RAND{1a|###RAND{2a|2b|2c|###RAND{3a|3b|3c|3
+d}|2d}|1b|1c|1d} some text';
print process_rands($string)."\n";
sub process_rands {
my $sentence = shift;
while (1) {
last
unless $sentence =~ s!###RAND\{([^{}]+)\}!get_rand_arr_
+el($1)!e;
print $sentence."\n";
}
return $sentence;
}
sub get_rand_arr_el {
warn Data::Dumper->Dump([\@_],[qw(*_)]),' ';
my @array = split '\|',$_[0];
my $randomelement = $array[ rand @array ];
return $randomelement;
}
yields
@_ = (
'3a|3b|3c|3d'
);
at play.pl line 18.
some text ###RAND{1a|###RAND{2a|2b|2c|3c|2d}|1b|1c|1d} some text
@_ = (
'2a|2b|2c|3c|2d'
);
at play.pl line 18.
some text ###RAND{1a|2b|1b|1c|1d} some text
@_ = (
'1a|2b|1b|1c|1d'
);
at play.pl line 18.
some text 1d some text
some text 1d some text
|