http://www.perlmonks.org?node_id=11157720

This scratched an itch for me, no guarantees.
use warnings::colored; warn "warning"; # yellow system "non-existant-command"; # red say "test"; # none eval { die "caught" }; # none say $@; # none die "died"; # red
And the implementation:
package warnings::colored; use strict; use warnings; use Term::ANSIColor; # Color die and warn messages. # NOTE: Doesn' play well with Carp::Always because it replaces our die + and # warn sighandlers. $ENV{NO_COLOR} = 1 if ! exists $ENV{NO_COLOR} and (! -t STDIN or ! -t STDERR); BEGIN { my $died; *CORE::GLOBAL::die = sub { $died = 1, print STDERR color('bold red') if @_ and ! $^S; END { $died && print STDERR color('reset') } $] >= 5.016 && goto &CORE::die; CORE::die @_; }; *CORE::GLOBAL::warn = sub { unshift @_, color('bold yellow'); # $SIG{__WARN__} will print the reset sequence. $] >= 5.016 && goto &CORE::warn; CORE::warn @_; }; } # Unintentional warning messages should display with high severity. # E.g.`system 'nonexistent-command'`. $SIG{__WARN__} = sub { my $msg = shift; if ($] < 5.016 and __FILE__ eq (caller)[1]) { my ($file, $line) = (caller(1))[1, 2]; $msg =~ s/( at .*? line \d+\.$)/ at $file line $line/m; } CORE::warn color('bold red'), $msg; print STDERR color('reset'); }; $SIG{__DIE__} = sub { my $msg = shift; if (__FILE__ eq (caller)[1]) { my ($file, $line) = (caller(1))[1, 2]; $msg =~ s/( at .*? line \d+\.$)/ at $file line $line/m; die $msg; } } if $] < 5.016 ; 1;

Replies are listed 'Best First'.
Re: Color die and warn messages
by dbuckhal (Chaplain) on Mar 02, 2024 at 06:28 UTC

    Hey, just silly thought I had regarding your "NOTE"

    # NOTE: Doesn' play well with Carp::Always because it replaces our die

    Since you are colorizing, instead of "die", use "dye" to prevent clobbering.

    Otherwise, cool concept!

    ... I really hope Anonymous Monk gets this response ...