B
Ben Morrow
I've been playing with overloading, and the following is puzzling
me... the script
#!/usr/bin/perl -l
use warnings;
use strict;
{{
package I;
use overload
"0+" => sub {
my $s = shift;
my $v = $$s;
print "numify";
0+$v;
},
q{""} => sub {
my $s = shift;
my $v = $$s;
print "stringify";
"$v";
},
"=" => sub {
my $s = shift;
my $v = $$s;
print "copy";
my $t = $v;
bless \$t;
},
"-" => sub {
my $s = shift;
my $v = $$s;
my $a = shift;
print "sub($a)";
$$s = (shift) ? $v - $a : $a - $v;
};
sub new {
my $c = shift;
my $s = shift;
bless \$s, $c;
}
}}
my $i = new I "*";
print $i;
print int($i);
print $i--;
__END__
prints
stringify
*
numify
Argument "*" isn't numeric in addition (+) at ./op line 15.
numify
Argument "*" isn't numeric in addition (+) at ./op line 15.
0
sub(1)
Argument "*" isn't numeric in subtraction (-) at ./op line 35.
stringify
1
about which I have two questions:
1. Why is 'numify' called twice for int($i)?
2. Why is 'numify' not called at all before calling '-'? OK, I guess
that makes sense... but why, then, will '-' not autogenerate in
terms of 'numify'? Is there any way to call it, without giving the
sub a name (i.e., is it possible to simply 'numify' a scalar, as
"$s" will stringify)?
Ben
me... the script
#!/usr/bin/perl -l
use warnings;
use strict;
{{
package I;
use overload
"0+" => sub {
my $s = shift;
my $v = $$s;
print "numify";
0+$v;
},
q{""} => sub {
my $s = shift;
my $v = $$s;
print "stringify";
"$v";
},
"=" => sub {
my $s = shift;
my $v = $$s;
print "copy";
my $t = $v;
bless \$t;
},
"-" => sub {
my $s = shift;
my $v = $$s;
my $a = shift;
print "sub($a)";
$$s = (shift) ? $v - $a : $a - $v;
};
sub new {
my $c = shift;
my $s = shift;
bless \$s, $c;
}
}}
my $i = new I "*";
print $i;
print int($i);
print $i--;
__END__
prints
stringify
*
numify
Argument "*" isn't numeric in addition (+) at ./op line 15.
numify
Argument "*" isn't numeric in addition (+) at ./op line 15.
0
sub(1)
Argument "*" isn't numeric in subtraction (-) at ./op line 35.
stringify
1
about which I have two questions:
1. Why is 'numify' called twice for int($i)?
2. Why is 'numify' not called at all before calling '-'? OK, I guess
that makes sense... but why, then, will '-' not autogenerate in
terms of 'numify'? Is there any way to call it, without giving the
sub a name (i.e., is it possible to simply 'numify' a scalar, as
"$s" will stringify)?
Ben