Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^6: Ter::ANSIColor is awesome, but.. (need help)

by mascip (Pilgrim)
on Mar 30, 2014 at 15:23 UTC ( #1080301=note: print w/ replies, xml ) Need Help??


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

I cannot overload eq() because Term::ANSIColor doesn't return an object. Ouch. Are there any alternative implementations out there that return an object?

It could look like this:

my $name = String::Colored->new('Jon', 'red'); # improvised module nam +e # Overloads stringification print $name; # Overloads string comparison operators my $res = $name eq 'Jon'; $name->stripcolor;


Comment on Re^6: Ter::ANSIColor is awesome, but.. (need help)
Download Code
Re^7: Ter::ANSIColor is awesome, but.. (need help)
by Corion (Pope) on Mar 30, 2014 at 16:04 UTC

    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.

      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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1080301]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2014-08-31 00:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls