This is just like ReadLine regexp quicktest except it tests a string for substitutions. You can screw it up just as in your own perl code! Again, if you have an instance where this doesn't hold true comment. To be clear:

  • string: give a string to be substituted from
  • replace: give a regexp pattern to replace
  • with: give a string to replace regexp pattern
  • suffix: something to follow the last "/", eg. smx

    And all the while you can shuffle up and down using the ReadLine command history...
  • #!/usr/bin/perl -w use strict; use Term::ReadLine; # for correction and command history you must have # Term::ReadLine::Gnu (from CPAN) installed my $term = new Term::ReadLine 'regexp Smode'; my $pr1 = "string: "; my $pr2 = "replace: "; my $pr3 = "with: "; my $pr4= "suffix: "; my $OUT = $term -> OUT || *STDOUT; my $output; while (1) { my $string = $term -> readline($pr1); my $replace = $term->readline($pr2); my $with = $term->readline($pr3); my $suffix = $term->readline($pr4); eval{ eval "(\$output = \$string) =~ s/\$replace/\$with/$suffi +x" }; print $OUT "$output\n"; }

    Replies are listed 'Best First'.
    Re: regexp s/mode quicktest
    by oko1 (Deacon) on Mar 25, 2008 at 04:16 UTC

      Rather than using individual scalars and temporary variables for each of the items, you should consider using a hash. In addition, it would be a good idea to provide a graceful exit out of the loop (e.g., typing 'exit' or 'quit' at any of the input lines should terminate it) and you should check for errors during the evaluation (which your double 'eval' swallows up.) Here's a quick cut at a revision:

      #!/usr/bin/perl -w use strict; use Term::ReadLine; my $term = new Term::ReadLine 'regexp Smode'; my $OUT = $term -> OUT || \*STDOUT; my %p; while (1){ for my $key (qw/string replace with suffix/){ $p{$key} = $term->readline("\u$key: "); exit if $p{$key} =~ /^(?:quit|exit)$/i; } eval "\$p{string} =~ s/\$p{replace}/\$p{with}/$p{suffix}"; print $OUT $@ ? "ERROR: $@\n" : "$p{string}\n\n"; }

      I've been using a somewhat similar gadget for years now - but I prefer actually writing out the regex, so I only read two parameters ('String' and 'Regex'). This also allows me to test 'tr's as well as 's///' operators. Thanks to your idea, I've just added 'Term::Readline' functionality to it, which makes it even more useful.