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

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

Replies are listed 'Best First'.
Re^4: die in regexp
by powerman (Friar) on Jul 03, 2006 at 20:39 UTC
    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.