http://www.perlmonks.org?node_id=2637

vroom has asked for the wisdom of the Perl Monks concerning the following question: (strings)

How do I compare two strings?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I compare two strings?
by turnstep (Parson) on Mar 29, 2000 at 21:44 UTC
    if ($string1 eq $string2){ print"\$string1 is equal to \$string2\n"; } elsif ($string1 lt $string2){ print"\$string1 is less than \$string2\n"; } elsif ($string1 gt $string2){ print"\$string1 is greater than \$string2\n"; }
    == tests equality for numbers.
    eq does the same for strings.
    lt is the string testing equivalent of the numerical <
    gt is the string testing equivalent of the numerical >

    You can also use the cmp operator, which is the non-numerical equivalent of the <=> operator:

    $result = $string1 cmp $string2;

    $result will be:

    • 0 if the strings are equal
    • 1 if string1 is greater than string2
    • -1 if string1 is less than string2
Re: How do I compare two strings?
by PipTigger (Hermit) on Jul 07, 2000 at 09:26 UTC
    As an addendum to turnstep's fine post: Another useful test is: ne ... as in:
    if ($string1 ne $string2) { print "\$string1 is not equal to \$string2\n"; }

    Just as: == tests equality between two numbers,
    != tests inequality for numbers and
    eq tests strings for equality as
    ne tests strings for inequality.
    I often find it useful to test
    if ($string0 ne "") { #use $string0 }
    to verify that a string has a value even if it's == 0.
Re: How do I compare two strings?
by gridlock (Novice) on Feb 21, 2004 at 04:36 UTC
    Depends on what kind of comparision: Strings can be tested for the following
    Equality - the eq operator
    Inequality - the ne operator
    Greater Than - the gt operator
    Greater or Equal - the ge operator
    Less than - the lt operator
    Less of Equal - the le operator


    Syntax:
    $stringtest = ($string1 eq $string2);
    Try replacing eq with the other operators.
      The inequality operator is ne.