vincentaxhe has asked for the wisdom of the Perl Monks concerning the following question:
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.#!/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: $!"; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: grep with color module of perl
by Fletch (Bishop) on Aug 05, 2024 at 05:43 UTC | |
by hippo (Archbishop) on Aug 05, 2024 at 11:30 UTC | |
by vincentaxhe (Scribe) on Aug 05, 2024 at 12:42 UTC | |
by vincentaxhe (Scribe) on Aug 05, 2024 at 12:15 UTC | |
Re: grep with color module of perl
by cavac (Prior) on Aug 05, 2024 at 05:39 UTC | |
by vincentaxhe (Scribe) on Aug 05, 2024 at 12:20 UTC | |
Re: grep with color module of perl
by johngg (Canon) on Aug 05, 2024 at 11:08 UTC | |
by vincentaxhe (Scribe) on Aug 05, 2024 at 12:07 UTC | |
Re: grep with color module of perl
by roho (Bishop) on Aug 06, 2024 at 06:01 UTC |