Overloaded operators: Difference between revisions

m
→‎{{header|Perl}}: revise code layout to emphasize parallelism
m (syntax highlighting fixup automation)
m (→‎{{header|Perl}}: revise code layout to emphasize parallelism)
Line 458:
so that they can be used on members of that class(package). Also see 'Zeckendorf arithmetic' where overloading
is used on Zeckendorf numbers.
<syntaxhighlight lang="perl">#!/usr/bin/perluse v5.36;
 
use strict; # https://rosettacode.org/wiki/Overloaded_operators
use warnings;
 
my $x = Ones->new( 15 );
my $y = Ones->new( 4 );
 
my $z = $x + $y;
print "$x + $y = $z\n";
$z = $x - $y;
print "$x - $y = $z\n";
$z = $x * $y;
print "$x * $y = $z\n";
$z = $x / $y;
print "$x / $y = $z\n";
 
package Ones;
use overload qw("" asstring + add - subtract * multiply / divide);
 
sub new ( $class, $value ) { bless \('1' x $value), ref $class || $class }
sub new
sub asstring ($self, $other, $) { $$self }
{
sub asdecimal ($self, $other, $) { length $$self }
my ( $class, $value ) = @_;
sub add ($self, $other, $) { bless \('1'$$self x. $value$other), ref $class || ref $class;self }
sub subtract ($self, $other, $) { bless \($$self =~ s/$$other//r), ref $self; }
}
sub multiply ($self, $other, $) { bless \($$self =~ s/1/$$other/gr), ref $self; }
 
sub divide ($self, $other, $) { $self->new( $$self =~ s/$$other/$$other/g ); }
sub asstring
{
my ($self, $other, $swap) = @_;
$$self;
}
 
sub asdecimal
{
my ($self, $other, $swap) = @_;
length $$self;
}
 
sub add
{
my ($self, $other, $swap) = @_;
bless \($$self . $$other), ref $self;
}
 
sub subtract
{
my ($self, $other, $swap) = @_;
bless \($$self =~ s/$$other//r), ref $self;
}
 
package main;
sub multiply
{
my ($self, $other, $swap) = @_;
bless \($$self =~ s/1/$$other/gr), ref $self;
}
 
my ($x,$y,$z) = ( Ones->new( 15), Ones->new(4) );
sub divide
print$z = $x + $y; say "$x + $y = $z\n";
{
$z = my$x - ($self,y; say "$other,x - $swap)y = @_$z";
print$z = $x * $y; say "$x -* $y = $z\n";
$self->new( $$self =~ s/$$other/$$other/g );
$z = }$x / $y; say "$x / $y = $z";</syntaxhighlight>
{{out}}
<pre>
2,392

edits