in reply to Drop in regex replacements?

Rather than explain the following snippet should give you an idea of what I'm trying to do. I just can't quite get it going and respectfully ask for the help of the monks.
Rather than explain it, here is my incomplete and untested (for lack of test data) solution:

sub replace { my ($tag,$attr,$content) = @_; $attr ||= $content; if ($tag eq 'b') { return "<b>$content</b>"; } elsif ($tag eq 'url') { return "<a href='$attr'>$content</a>"; } # etc. etc. etc. } s/\[(\w+)=?(\w*)\](\w+)\[\1\]/replace($1,$2,$3)/esg;
Hope this helps :-)

Update:
Ok, let's explain it a little anyway: I've turned your problem inside out, so you only need 1 regex and only 1 s statement. This has 3 advantages:

You might need a little finetuning on this code (I haven't tested it except for syntax) but I think this is a lot easier and maintainable way of solving your problem.
-- Joost downtime n. The period during which a system is error-free and immune from user input.

Replies are listed 'Best First'.
Re: Re: Drop in regex replacements?
by IOrdy (Friar) on Sep 09, 2002 at 14:58 UTC
    Sorry, I thought it would be quite obvious because above each regex is an example of what I am parsing. :-(
    # Process Complex Tags -> [url="http://www.foo.bar.com"]foobar[/url]
    What you suggested would be longer than just cutting/pasting and running a complete regex for every tag. shame.
      Please read my above explanation for what I am doing here.

      I am changing the problem around to make it easier to maintain and expand. If you really need to have compact code, you can change the &replace sub like this:

      my %replaces = ( email => sub { "<a href=mailto:'$_[0]'>$_[1]</a>" }, url => sub { "<a href='$_[0]'>$_[1]</a>'" }, # etc etc etc ); sub replace { my ($tag,$attr,$content) = @_; $attr ||= $content; return $replaces{$tag}->($attr,$content); }
      I was merely trying to make the code as clean and clear as I could.
      -- Joost downtime n. The period during which a system is error-free and immune from user input.