Overloaded operators: Difference between revisions

Line 280:
 
Otherwise, precedence is determined by the first character.
 
=={{header|Perl}}==
See 'perldoc overload' for perl's overload capabilities. This example defines a class(package)
that represent non-negative numbers as a string of 1's and overloads the basic math operators
so that they can be used on members of that class(package).
<lang perl>#!/usr/bin/perl
 
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
{
my ( $class, $value ) = @_;
bless \('1' x $value), ref $class || $class;
}
 
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;
}
 
sub multiply
{
my ($self, $other, $swap) = @_;
bless \($$self =~ s/1/$$other/gr), ref $self;
}
 
sub divide
{
my ($self, $other, $swap) = @_;
$self->new( $$self =~ s/$$other/$$other/g );
}</lang>
{{out}}
<pre>
111111111111111 + 1111 = 1111111111111111111
111111111111111 - 1111 = 11111111111
111111111111111 * 1111 = 111111111111111111111111111111111111111111111111111111111111
111111111111111 / 1111 = 111
</pre>
 
=={{header|Phix}}==
Anonymous user