Howdy Monks,
A Format object creates and holds an instance of its parent object, Format::Real. AUTOLOAD is then used to propagate method calls up to the parent. More of a wrapper than real inheritance I guess.
Seems clean to me, but if I do this, will I be sorry later? Should I be more conventional and use ISAs and SUPERs?
YuckOo
#!/usr/bin/perl
use strict;
my $as_float_e = Format->new('%8.4e');
my $as_float = Format->new('%8.4f');
my $as_integer = Format->new('%d');
my $as_string = Format->new('%20.20s');
my $var = 1234.5678;
print $as_float_e ->format($var), "\n";
print $as_float ->format($var), "\n";
print $as_integer ->format($var), "\n";
print $as_string ->format($var), "\n";
#-----------------------------------------------------------
package Format;
#-----------------------------------------------------------
sub new {
my ($pack, $spec) = @_;
my $r = {};
$r->{real} = Format::Real->new();
$r->{spec} = $spec;
bless $r, $pack;
}
#-----------------------------------------------------------
sub AUTOLOAD {
my $r = shift;
my $func = (split('::', $Format::AUTOLOAD))[-1];
if (Format::Real->can($func)) {
$r->{real}->$func($r->{spec}, @_);
}
}
#-----------------------------------------------------------
package Format::Real;
#-----------------------------------------------------------
sub new {
my ($pack) = @_;
bless {}, $pack;
}
#-----------------------------------------------------------
sub format {
my $r = shift;
my ($spec, $num) = @_;
sprintf $spec, $num;
}