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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With