This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
out.print(x);
"... This method calls at first String.valueOf(x) to get the printed object's string value ..."
record X<T>(T t) {
@Override
public String toString() {
String s = t.getClass().getName();
s = "%s<%s>".formatted(getClass().getName(), s);
return "%s@%x".formatted(s, identityHashCode(this));
}
}
X<?> x = new X<>(123);
out.print(x);
class Point {
has $x :param = 0;
has $y :param = 0;
use overload '""' => sub { shift->_stringify() };
method _stringify () { "A point at ($x, $y)" }
}
my $p = Point->new(x => 5, y => 10);
print $p; # prints: A point at (5, 10)
Perl doesn't have user-defined types, but perl has classes.
This is an example using the Object::Pad module to define a class, and then using overload on the string operator. This will also work with other OO modules like Moose and Moo.
The shift operation in the sub gets the object off the argument list to the anon sub, so it can be used for the call to the associated stringify method.
This is an example using the Object::Pad module to define a class, and then using overload on the string operator. This will also work with other OO modules like Moose and Moo.
The shift operation in the sub gets the object off the argument list to the anon sub, so it can be used for the call to the associated stringify method.
package Point {
my $_data = {};
sub new {
my $class = shift;
$_data = { @_ };
bless $_data, $class;
};
use overload '""' => sub { shift->_stringify() };
sub _stringify {
my $self = shift;
return sprintf 'A point at (%d, %d)', $self->{x}, $self->{y};
}
}
my $p = Point->new(x => 5, y => 10);
print $p;
This solution forgoes modern OO modules like Moose or Object::Pad and instead uses classic perl roll-your-own OO using a package for a class. Advantage: works on platforms with out of date libraries (like the demo platform).