Search code examples
perlobjectoverloadingmoose

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?


Solution

  • 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