Search code examples
stringperlequalitytruthiness

Is there a string in Perl that is equal to all other strings under eq?


I am running a string equality check like this:

if($myString eq "ExampleString")

Is there a value that myString could have which would cause execution to enter the if structure no matter what the string literal is?


Solution

  • Yes, with objects and overloaded operators:

    package AlwaysTrue {
      use overload 'eq' => sub { 1 },
                   '""' => sub { ${+shift} };
      sub new {
        my ($class, $val) = @_;
        bless \$val => $class;
      }
    }
    
    my $foo = AlwaysTrue->new("foo");
    
    say "foo is =$foo=";
    say "foo eq bar" if $foo eq "bar";
    

    Output:

    foo is =foo=
    foo eq bar
    

    However, "$foo" eq "bar" is false, as this compares the underlying string.