views:

3063

answers:

4

How do I compare two strings in Perl?

I am learning Perl, I had this basic question looked it up here on StackOverflow and found no good answer so I thought I would ask.

+10  A: 

See perldoc perlop. Use lt, gt, eq, ne (thanks tuckster) and cmp as appropriate.

Sinan Ünür
Just one more, ne for not equal.
tuckster
You might want to mention that $str1 =~ "$str2" (not /$str2/) will check if $str2 is a substring of $str1.
Daniel
@Daniel use `index` to see if a string is a substring of another one.
Sinan Ünür
@Daniel: there's not much practical difference between =~"$str2" and =~/$str2/ (or just =~$str2 for that matter); index is the right tool, but if you need to use a regex for some reason, do =~/\Q$str2\E/.
ysth
+2  A: 
print "Matched!\n" if ($str1 eq $str2)

Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.

Matthew Scharley
+11  A: 
  • cmp Compare

    'a' cmp 'b' # -1
    'b' cmp 'a' #  1
    'a' cmp 'a' #  0
    
  • eq Equal to

    'a' eq  'b' #  0
    'b' eq  'a' #  0
    'a' eq  'a' #  1
    
  • ne Not-Equal to

    'a' ne  'b' #  1
    'b' ne  'a' #  1
    'a' ne  'a' #  0
    
  • lt Less than

    'a' lt  'b' #  1
    'b' lt  'a' #  0
    'a' lt  'a' #  0
    
  • le Less than or equal to

    'a' le  'b' #  1
    'b' le  'a' #  0
    'a' le  'a' #  1
    
  • gt Greater than

    'a' gt  'b' #  0
    'b' gt  'a' #  1
    'a' gt  'a' #  0
    
  • ge Greater than or equal to

    'a' ge  'b' #  0
    'b' ge  'a' #  1
    'a' ge  'a' #  1
    

See perldoc perlop for more information.

Brad Gilbert
+3  A: 
Chas. Owens
+1 I love the smart match operator ;-)
Sinan Ünür
It's not changing slightly: it's changing radically. Smart matching for anything un-simple is seriously broken.
brian d foy