Can I control the value of a Moose object when used in a scalar context?

Is it possible (and reasonably) to change the value that the Moose object evaluates in a scalar context. For example, if I do

my $object = MyObject->new(); print $object; 

Instead of typing something like:

 MyObject=HASH(0x1fe9a64) 

Can I print another custom line?

+4
source share
3 answers

Look at the overload pragma. I don't think you can overload the scalar context, but try overloading the structure (which is denoted by "" , which you must quote to become silly looking '""' , citing the use of the q operator, make it more readable).

 #!/usr/bin/env perl use strict; use warnings; package MyObject; use Moose; use overload q("") => sub { return shift->val() }; has 'val' => ( isa => 'Str', is => 'rw', required => 1); package main; my $obj = MyObject->new( val => 'Hello' ); print $obj; # Hello 
+6
source

The following may also save you from scratching your head:

use namespace::autoclean; , which is sometimes mentioned / proposed in relation to Musa, is incompatible with use overload q("")...

What usually happens is that you drop use namespace::autoclean; and then use overload q("")... works fine.

+2
source

Yes, you can. See the overload "" .

To decide if this is reasonable is up to you. eight)

+1
source

Source: https://habr.com/ru/post/1389675/


All Articles