in reply to regex find and replace with a twist

For this example, at least, I don't think I'd bother with a regex. Instead, I'd split the string up into individual characters, process each character, and join the results back into a string:
my $word = 'layer'; my $new_word = join '', map { "[$_]" } split '', $word; # Or, if I want to be more explicit about the process: # my @raw_chars = split '', $word; # my @cooked_chars = map { "[$_]" } @raw_chars; # my $new_word = join '', @cooked_chars;

Edit: As pointed out in replies, the spec was to only bracket characters in the range a-zA-Z, not all characters. This can be fixed with a minor adjustment to the map. Change it to map { $_ =~ /[a-zA-Z]/ ? "[$_]" : $_ } and you get the result:

$ perl -E '$word = "layer123 $-.% foo"; $new_word = join "", map { $_ +=~ /[a-zA-Z]/ ? "[$_]" : $_ } split "", $word; say $new_word;' [l][a][y][e][r]123 0.% [f][o][o]

Replies are listed 'Best First'.
Re^2: regex find and replace with a twist
by AnomalousMonk (Archbishop) on Jul 17, 2018 at 15:29 UTC

    I think a split-based solution (which I personally would not use) would have to look something like this to get what seems (I think) to be the required output:

    c:\@Work\Perl\monks>perl -wMstrict -le "my $word = '$-.%aBc&/'; my $new_word = join '', map { /[[:alpha:]]/ ? qq{[$_]} : $_ } split '', $word ; print qq{'$word' -> '$new_word'}; " '$-.%aBc&/' -> '$-.%[a][B][c]&/'
    Since this depends on two regexes, I think you might as well use a  s/// approach and be done with it.


    Give a man a fish:  <%-{-{-{-<

Re^2: regex find and replace with a twist
by Anonymous Monk on Jul 17, 2018 at 07:36 UTC
    what if $word = '$-.%'?

      That's simple to try .. I suspect you didn't try it.

      tab@music3:~/2018-0717$ cat pm.pl #!/usr/bin/perl use strict; use warnings; { my $word = '$-.%'; my $new_word = join ( '', map { "[$_]" } split '', $word ); print "$word -> $new_word\n"; } tab@music3:~/2018-0717$ perl pm.pl $-.% -> [$][-][.][%] tab@music3:~/2018-0717$

      Perl doesn't care what's in the string -- more specifically, split doesn't have problems with any characters that may have special meaning in a regex.

      Alex / talexb / Toronto

      Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

        $-.% -> [$][-][.][%]

        Note the OP said (emphasis mine):

        I need to find any letter [a-zA-Z] and replace it