> On Jun 3, 2018, at 7:41 PM, Xin Cheng <xinchen...@gmail.com> wrote:
> 
> I am trying to make a program to do grep with perl6 regular expression, and I 
> would like to colorize the matched part to the terminal.
—snip--
>         if $temp ~~ s/ (<$pattern>) /\\x1b\[31m$0\\x1b\[0m/ {say $temp}

—snip—

Change this:    s/ (<$pattern>) /\\x1b\[31m$0\\x1b\[0m/
to this:                s/ (<$pattern>) /\x1b[31m$0\x1b[0m/
and your example code will correctly highlight the pattern in the (terminal) 
output.

The doubled backslash in your original code becomes a literal backslash; 
“\\x1b” is 4 characters long, “\x1b” is 1 character long (the escape 
character). Also, you would need to back-whack the `[` only on the left-hand 
side of `s///` (the pattern, which uses Regex syntax), not on the right-hand 
side (the replacement, which uses double-quoted string syntax).

If you do not want to use Terminal::ANSIColor, I recommend that you save 
yourself some future confusion by isolating your escape sequences, like so:

constant $color_red = "\e[31m";
constant $color_off = "\e[0m";

sub MAIN ( Str $pattern, Str $filename ) {
    for $filename.IO.lines -> $line  {
        my Str $temp = $line;

        # if no <> surrounding $pattern it becomes literal.
        if $temp ~~ s/ (<$pattern>) /$color_red$0$color_off/ { 
            say $temp;
        }
    }
}

— 
Hope this helps,
Bruce Gray (Util of PerlMonks)

Reply via email to