Q:

Coloring tail output with perl

tail -f logfile.log | perl -pe 's/.*foo*/\e[1;41m$&\e[0m/g'    

will color all the lines containing the pattern "foo" in the logfile.log file. 
How can I make use of this in order to highlight not the whole line but just the exact pattern? 
echo "WARN ERROR foo"|sed 's#WARN#\x1b[33m&#; s#ERROR#\x1b[31m&#; s#foo#\x1b[32m&#'    

I mean if I want to do something like this, how can I manage?

A:

First of all, you can use almost the exact same regular expression and syntax as you did with sed. Just change & to $& for Perl:
echo "WARN ERROR foo" | 
    perl -pe 's#WARN#\x1b[33m$&#; s#ERROR#\x1b[31m$&#; s#foo#\x1b[32m$&#'    

Or, using your original Perl approach, just remove the .* on either side of the pattern you want to match:
tail -f logfile.log | perl -pe 's/foo/\e[1;41m$&\e[0m/g'    

For a more versatile approach, you can use the little script I have posted in my answer here. With it, you can color up to 10 patterns with a different color for each. For example, to color the words ERROR,WARNING and foo, in a different color, case-insensitively: 
tail -f logfile.log | color.pl -il "error,warning,foo"

