in reply to regex switch trouble

I don't know why the switch is not valid there, but anything that complex should be hoisted out of the replacement anyway. This works:

use strict; use warnings; use Switch; my $text = 'bla fred wilma fuck fred fuck wilma bla fred fredfred'; sub replace_it { switch( $_[0] ) { case 'fred' { return 'wilma' } case 'wilma' { return 'fred' } die; }; } $text =~ s{(fred|wilma)}{replace_it($1)}eg; print $text;

Replies are listed 'Best First'.
Re^2: regex switch trouble
by spx2 (Deacon) on Jun 14, 2007 at 01:37 UTC
    so is it because its embedded in the regex ? why is it so hard to implement switch in a proper manner ?
      When you put executable perl code into the replacement (right-hand) portion of  s///e, I think you are by nature using "eval" to execute that code. Therefore, you run up against this little detail described in the man page for Switch (under the section heading "LIMITATIONS"):
      Due to the way source filters work in Perl, you can't use Switch inside a string "eval".
      The reference to "source filters" there has to do with how the Switch module is implemented. When you use it, the code that ends up being executed is actually different in significant ways from the code that you wrote. That's why many people (including the author of the module) advise against using Switch in "production code" (i.e. for anything that needs to be rock-solid and readily maintainable).

      As GrandFather pointed out, there are better ways to do what you need to do in this case.

        When you put executable perl code into the replacement (right-hand) portion of s///e , I think you are by nature using "eval" to execute that code.

        Nope, that's /ee, which in fact is discouraged and rarely used nowadays, that I can see. /e is not associated with the same issues. Thinking of all these matters, however, one can only appreciate even more how good they are doing with the new rules.

      Switch replaces the Perl parser with its own that understands the switch statement. However, Perl's parser is quite complex. Instead of re-implementing Perl, Switch takes some shortcuts which makes it malfunction in certain cases.