Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Instead of printing something like:

MyObject=HASH(0x1fe9a64)

Can I make it print some other custom string?

like image 297
lexicalscope Avatar asked Jan 17 '23 21:01

lexicalscope


2 Answers

Look into the overload pragma. I don't think you can overload scalar context, but try overloading stringification (which is denoted by "", which you must quote becoming the silly looking '""', quoting using the q operator make this 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
like image 135
Joel Berger Avatar answered Jan 25 '23 23:01

Joel Berger


The following may also save you some head scratching:

use namespace::autoclean;, which is sometimes mentioned/suggested in relation to Moose, is not compatible with use overload q("")....

Generally what happens is that you drop the use namespace::autoclean;, and then the use overload q("")... works fine.

like image 32
zgpmax Avatar answered Jan 26 '23 00:01

zgpmax