in reply to Efficiently create an IF/ELSE regex

If there are no other spaces:

use strict; use warnings; my @incoming = ( "AD\thomas", "MAIN\nancy", "FOO\randy", "nancy", ); my %whitespace = ( "\n" => "n", "\t" => "t", "\r" => "r", "\f" => "f", ); for (@incoming) { print "$_: "; s/(\s)/\\$whitespace{$1}/g; print "$_\n"; }

(stealing some code from above...)

Replies are listed 'Best First'.
Re^2: Efficiently create an IF/ELSE regex
by jcrush (Acolyte) on May 01, 2015 at 19:51 UTC

    Thank you, this is what I was looking for:

    my %whitespace = ( "\n" => "n", "\t" => "t", "\r" => "r", "\f" => "f", ); my $fixid =~ s/(\s)/\\$whitespace{$1}/g;

    I find it more efficient to complete a full test, than test multiple times.

    Thanks,

    jcrush

      Unless you want to modify default variable $_ & save the number of replacements, there is typo in your s/// application. In that case, op should be (to save the result of all of replacements in another string) ...

      ( my $fixed = $input ) =~ s/ search / replace /x;

      For fun, try the proposed s/(\s)/\\$whitespace{$1}/g solution on string x y (a plain space in between).