I often have requests to comment out BLOCKS of text, such as "comment out everything between and including each cat/^cat block. Example:
mouse
cat
1
2
3
^cat
deer
eel
cat
furbaby
elk
^cat
dog
fish
the result I want is
mouse
#cat
#1
#2
#3
#^cat
deer
eel
#cat
#furbaby
#elk
#^cat
dog
fish
This can be in an array (one element per line) or a scalar. Usually I just loop thru the list and set a flag when hit cat, and unset it after leaving ^cat, and add the # if flagged. Which is like how I would do this in C. Every time I solve a problem in my brain in C, I always think to myself
surely Perl has a better approach!.. Fugly code:
my $comment=0;
for (@a) {
$comment++ if /^cat\b/;
$_ = '#'.$_ if $comment;
$comment-- if /^\#\^cat\b/;
}
Can you suggest a brief solution with a single no-looping regex, OR a map for an array? Or maybe a clever mapped split?
Much thanks and happy Day of the Earth-Rodent-Forecaster!