Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

If you mean "any string other than undef", then simply check

if (defined $myString)

If you mean "any string other than undef or empty string", then simply check

if ($myString) # Has a slight bug - will NOT enter if the number 0 passed
#or
if ($myString || $myString == 0)  # Avoids the above bug

If you mean ANY ANY string, you don't need an if.... but if you want one anyway:

if (1)

If you mean "any string that isn't looking like a number" (e.g. distinguish "11" from "11a"):

use Scalar::Util qw(looks_like_number);
if (Scalar::Util::looks_like_number($myString))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top