"Sputnik" help  
Sputnik Help
Language Reference - Classes - Class Operator Overrides - Equate

Class Operator Overrides - Equate

This allows a class to override the == (equate) operator example:

class Test
{
    my $i;
    my $j;
    Function __Construct($i, $j)
    {
        @this->$i = $i;
        @this->$j = $j;
    }
    Function __OpEquate($x)
    {
        say "Compare == function is being run";
        return @this->$i == $x->$i && @this->$j == $x->$j;
    }
}

my $a = new Test(10, 20);
my $b = new Test(10, 22);

say "Compare with different numbers";
if ($a == $b)
{
    say "Same";
}
else
{
    say "Not Same";
}
say "Now making both same numbers then compare";
$b->$j = 20;
if ($a == $b)
{
    say "Same";
}
else
{
    say "Not Same";
}

// PRINTS
// Compare with different numbers
// Compare == function is being run
// Not Same
// Now making both same numbers then compare
// Compare == function is being run
// Same

Of course its possible to check if the input is a class or variable and act appropiately for example:

class Test
{
    my $i;
    my $j;
    Function __Construct($i, $j)
    {
        @this->$i = $i;
        @this->$j = $j;
    }
    Function __OpEquate($x)
    {
        // check if $x is a test class
        if ($x ~~ Test)
        {
            say "Compare == function is being run (with a class)";
            return @this->$i == $x->$i && @this->$j == $x->$j;
        }
        else
        {
            // so it is not a test class lets use it as a number
            say "Compare == function is being run (without a class)";
            return @this->$i == (int)$x && @this->$j == (int)$x;
        }
    }
}

my $a = new Test(10, 10);
my $b = new Test(10, 11);

say "Compare with different numbers";
if ($a == $b)
{
    say "Same";
}
else
{
    say "Not Same";
}
say "Now making both same numbers then compare";
$b->$j = 10;
if ($a == $b)
{
    say "Same";
}
else
{
    say "Not Same";
}
say "Now compare it a number";
if ($a == 10)
{
    say "Same";
}
else
{
    say "Not Same";
}

// PRINTS
// Compare with different numbers
// Compare == function is being run (with a class)
// Not Same
// Now making both same numbers then compare
// Compare == function is being run (with a class)
// Same
// Now compare it a number
// Compare == function is being run (without a class)
// Same

A full list of all possible operator overrides can be found here.


Contact
Cheryl (uberfox@hotmail.com)
Homepage
http://ubersoft.org