vincentaxhe has asked for the wisdom of the Perl Monks concerning the following question:

I have a paragrep.pl script to grep words showing in paragraph.
#!/bin/perl use Getopt::Std; use utf8::all; use v5.36; my %options; getopts("a",\%options); my $togrep = shift; $togrep = qr/$togrep/; my $lastfile = ""; local $/ = ""; sub printfound($found, $file, $lastfile){ print "#" x 10, "\n#$file\n" , "#" x 10, "\n" if $file ne $lastfil +e; my ($postmatch, @string); while ($found =~ /(?s)(.*?)(?-s)($togrep)/gp){ my $prematch = $1; my $match = $2; $postmatch = ${^POSTMATCH}; $match =~ s/^/\e[1;31m/mg; $match =~ s/$/\e[0m/mg; push @string, $prematch, $match; } push @string, $postmatch; print join '', @string; return $file } while (<>) { if ($options{a}){ $lastfile = printfound $_, $ARGV, $lastfile if /$togrep/i; }else{ $lastfile = printfound $_, $ARGV, $lastfile if /\A.*$togrep/i; } } if ($!) { die "unexpected error while reading from: $!"; }
I write this printfound subroutine to insert color start and end , it's a mess.now I have more needs to colorize matched pattern, I guess there must some module can do the work nicely.

Replies are listed 'Best First'.
Re: grep with color module of perl
by Fletch (Bishop) on Aug 05, 2024 at 05:43 UTC

    Probably Term::ANSIColor is what you’re looking for; that being said though ripgrep already exists (or App::Ack if you have to stay Perl for some reason).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

        you are like the history elder in movie 'Furiosa: A Mad Max Saga'!
      Ack is worthy digging, but it seems the only way to use it as an system command, I donot want fork anything.
Re: grep with color module of perl
by cavac (Prior) on Aug 05, 2024 at 05:39 UTC
      much interesting stuff, terminal color things. What bothers me in the script is to find a smart way to insert color control sequence repeatly like grep did.
Re: grep with color module of perl
by johngg (Canon) on Aug 05, 2024 at 11:08 UTC
    Here is a script that employs use Term::ANSIcolor qw{ :constants }; to highlight parts of a command output in different colours. Perhaps it will help you move forward.

    Cheers,

    JohnGG

      yeah, test good, that's what I want, It's much concise, what I write before is so inane.
      use Term::ANSIColor qw{ :constants }; while(<>){ s/(hello)/RED . $1 . RESET/eg; print }
Re: grep with color module of perl
by roho (Bishop) on Aug 06, 2024 at 06:01 UTC
    Just a quick note for those using Windows. The following module is also needed along with "Term::ANSIColor qw(:constants)" to display colors on the terminal:
    Win32::Console::ANSI;

    "It's not how hard you work, it's how much you get done."