in reply to Re^3: die in regexp
in thread die in regexp

Nice example, :) but no, my task can't be converted to something like this. Here is complete story. I've template like: "some text @~var1~@ some other text @~var 2~@ end of text" and I've this hash: { "var1" => $value1, "var 2" => $value2, }. So:
$tmpl =~ s/@~(.*?)~@/$hash{$1}/g;
But I wish to add some protection here. Minimum:
$tmpl =~ s/@~(.*?)~@/ defined $hash{$1} ? $hash{$1} : croak("@~$1~@ not defined") /ge;
Maximum - also detect orphaned @~ and ~@ like in this example: "some ~@ text @~ here @~".

Replies are listed 'Best First'.
Re^5: die in regexp
by graff (Chancellor) on Jul 03, 2006 at 21:51 UTC
    Here is complete story.

    Thanks -- this was brief and clear enough that you should have put that into the OP, instead of making up a "pseudo/generic" case to confuse us. :)

    Anyway, I would tend to prefer taking a two-step approach: apply all the substitutions that work, and after those are all done, if any residual template-variable markers are left behind, then croak. Something like this:

    my %hash = ( var1 => 'value1', var2 => 'value2' ); # ... or whatever... while ( $tmpl =~ /@~(.*?)~@/ and exists( $hash{$1} )) { my $var = $1; $tmpl =~ s/@~$var~@/$hash{$var}/g; } croak "Bad template text:\n$tmpl" if ( $tmpl =~ /@~|~@/ );
    "Basic" regex substitutions tend to be obscure and cryptic enough by themselves, without adding flow-control logic into the rhs. The code will be easier to maintain if you segregate the regex operations from the flow-control.