in reply to Re^6: Ter::ANSIColor is awesome, but.. (need help)
in thread Term::ANSIColor is awesome, but.. (need help)

Why not implement that yourself?

package MyApp::User; use strict; use overload '""' => \&stringify, 'eq' => \&cmp, ; sub new { my( $class, %options )= @_; bless \%options => $class; }; sub stringify { my( $self )= @_; colorize( $self->{ name }, 'red' ); }; sub cmp { ... };

In the long run, this approach of adding more magic instead of cleanly separating display logic and business logic in your program will cause you lots of problems. Most likely you will encounter unintentional stringification. But that's an experience you'll have to make yourself.

Replies are listed 'Best First'.
Re^8: Ter::ANSIColor is awesome, but.. (need help)
by mascip (Pilgrim) on Mar 30, 2014 at 16:17 UTC

    Oh yes, I just need a very thin wrapper. I should stop working on the weekend: I'm too tired to think. I imagined I'd have to refactor Term::ANSIColor into a class.

    It could look like this instead (more generic):

    package String::Colored; sub new { my( $class, $string, $color )= @_; bless { string => $string, color => $color } => $class; }; sub stringify { my( $self )= @_; colored( $self->{ name }, $self->{$color} ); } sub eq { ... }
    I like the idea.

    But I read your advice and now I'm wondering.
    Do you think you could give me the simplest example of how I might encounter unintentional stringification?

    I'm heading back home, I'll think about this tonight.

      If you are using $name as the key for a hash, it will get stringified.

      If you use @foo eq @bar to do a quick check whether two arrays (roughly) contain the same elements, the stringified elements will be compared.

        Haha, dammit!

        So... what I want is to always stringify my String::Colored object as a colorless string... unless when it's being printed on the screen.

        Is there any way to know that a text is being displayed on the screen? There's no "printing on screen" operator unfortunately ;-)

        print() indicates that we're in string context, which forces the stringification. So nothing will help my object know whether it's being printed or used as a hash key.

        That's annoying... I'll keep it in mind, in case I come up with a workaround. Otherwise I'll have to either abandon colors, think about re-organizing my code, or write colored() everywhere. I've got time to think...

        If only there was a "printing on screen" context...
        Or is that a silly idea?

        Thanks a lot for your help Corion :-)