Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

How do I compare two strings?

( #2637=categorized question: print w/ replies, xml ) Need Help??
Contributed by vroom on Feb 01, 2000 at 07:39 UTC
Q&A  > strings

Answer: How do I compare two strings?
contributed by turnstep

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
Answer: How do I compare two strings?
contributed by PipTigger

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.
Answer: How do I compare two strings?
contributed by gridlock

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

$stringtest = ($string1 eq $string2);
Try replacing eq with the other operators.


  • Please read these before you post! —
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others chanting in the Monastery: (4)
    As of 2016-08-27 04:41 GMT
    Find Nodes?
      Voting Booth?
      The best thing I ever won in a lottery was:

      Results (377 votes). Check out past polls.