Cody Fendant has asked for the wisdom of the Perl Monks concerning the following question:
I'm working with some code which frequently uses this … idiom I guess you'd call it?
use overload '""' => sub {shift->name;};
So I've read the Perldoc and it has this example:
package Number; use overload [snipped] '""' => sub { ...; };
which says it's "an anonymous subroutine to implement stringification: this is called whenever an object blessed into the package Number is used in a string context (this subroutine might, for example, return the number as a Roman numeral)."
So I guess, something like this?
### example package package Number; my $self = {}; sub new { my $class = shift(); $self->{decimal} = shift(); return bless( $self, $class ); } my @roman_numbers = qw[ undef I II III IV V VI VII VIII IX X ]; use overload '""' => sub { return $roman_numbers[ $self->{decimal} ] }; 1; ### main package main; my $instance = new Number(3); print $instance; ### it will print 'III'
So, two questions:
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: What's the point of this 'overload' idiom?
by hv (Prior) on Dec 07, 2022 at 04:56 UTC | |
by stevieb (Canon) on Dec 07, 2022 at 05:13 UTC | |
by LanX (Saint) on Dec 07, 2022 at 14:25 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 08, 2022 at 12:40 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 08, 2022 at 12:40 UTC | |
by Cody Fendant (Hermit) on Dec 07, 2022 at 07:01 UTC | |
by stevieb (Canon) on Dec 07, 2022 at 07:33 UTC | |
Re: What's the point of this 'overload' idiom? (updated)
by LanX (Saint) on Dec 07, 2022 at 14:08 UTC | |
Re: What's the point of this 'overload' idiom?
by ikegami (Patriarch) on Dec 08, 2022 at 21:25 UTC |