Search code examples
perlconditional-operatorcomma-operator

Perl period vs comma operator


Why does

print "$str is " , ispalindrome($str) ? "" : " not" , " a palindrome\n" 

print "madam is a palindrome", but

print "$str is " . ispalindrome($str) ? "" : " not" . " a palindrome\n"

prints ""?


Solution

  • The conditional operator (? :) has higher precedence than the comma, but lower than the period. Thus, the first line is parsed as:

    print("$str is " , (ispalindrome($str) ? "" : " not"), " a palindrome\n")
    

    while the second is parsed as:

    print(("$str is " . ispalindrome($str)) ? "" : (" not" . " a palindrome\n"))