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

I know how I can avoid this issue. :-) I don't know is I should avoid it. :) Also, I can't avoid it so ease - I need to do s/// in some complex template, and I wish to detect errors in this template. Example with "qwe" can be converted to simple m//, but not my real task. My real task can be converted to something like:
while (1) { $tmpl =~ /\G(...)/gcs && do { if ($1 eq "w") { croak "w is bad"; } else { $result .= process_template($1); } } || $tmpl =~ /\G(...)/gcs && do { ...do.something.else... } || last; }
You see, it's too complex to replace current single-line s/// just to be able to croak() on errors. :(

Replies are listed 'Best First'.
Re^3: die in regexp
by Hue-Bond (Priest) on Jul 03, 2006 at 20:05 UTC
    My real task can be converted to something like

    ...this?

    use Tie::IxHash; tie my %dt, 'Tie::IxHash', qr/one/ => \&handle_one, qr/two/ => \&handle_two; my $c="trigger one trigger two"; sub handle_one { print "one: ", shift, "\n"; } sub handle_two { print "two: ", shift, "\n"; } foreach (keys %dt) { $c =~ /\G.+?($_)/gcs and $dt{$_}->($1); }

    --
    David Serrano

      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 @~".
        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.