Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Color die and warn messages

by Anonymous Monk
on Feb 15, 2024 at 23:50 UTC ( [id://11157720]=CUFP: print w/replies, xml ) Need Help??

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 ...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://11157720]
Approved by Discipulus
Front-paged by Discipulus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (6)
As of 2024-05-19 06:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found