Karan
Karan

Reputation: 15094

How to overload strings in perl

I was trying to overload classes to strings in perl. For example:

use MooseX::Declare;

class overloadingInPerl{
    use overload '""' => sub {shift->printOut()};


    method printOut(){
       return "Overloading worked";
    }
}


my $overloadingTrial = overloadingInPerl->new();
print $overloadingTrial;

prints out: overloadingInPerl=HASH(0x1f520fc)

want to print: Overloading worked

Any ideas?

Upvotes: 2

Views: 292

Answers (2)

Carlos Lima
Carlos Lima

Reputation: 4182

Other than adding the dirty trait, as pointed by @oylenshpeegul you can also drop the coderef calling the actual function by passing its name as string and removing the () from the method declaration.

Errrm, easier showed than said.

#!/usr/bin/env perl                                                               
use Test::More tests=>1;                                                          
use MooseX::Declare;                                                              
class C is dirty {                                                                
    use overload '""' => 'to_string';                                             
    method to_string { sprintf "#<%s data='%s'>", $self->meta->name, $self->data }
    has data => (is=>'rw',default=>'');                                           
}                                                                                 
is(C->new(data=>'hello'), "#<C data='hello'>");                                   

Upvotes: 1

oylenshpeegul
oylenshpeegul

Reputation: 3424

You have to add the dirty trait to use overloading

class overloadingInPerl is dirty {

Upvotes: 3

Related Questions