3

I am working on a small script using Perl and i am confused which logical operator has to be used for comparing strings

Sample Code :

if (($app eq "appname1")OR($app eq "appname2")OR($app eq "appname3"))

Do i have to use OR (or) ||

zdim
  • 64,580
  • 5
  • 52
  • 81
Sampath
  • 41
  • 4
  • 1
    They are the same, except that `or` has much lower precedence. See [about it in perlop](http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or). This does imply differences in use, but in your example you can use either. Also, find the precedence table in the same page. – zdim Feb 10 '17 at 06:54
  • Related: http://stackoverflow.com/questions/1512547/what-is-the-difference-between-perls-or-and-and-short-circuit-o, http://stackoverflow.com/questions/1136583/what-is-the-difference-between-and-or-in-perl – mob Feb 10 '17 at 14:55

2 Answers2

6

The general rule of thumb tends to be:

  • Use || to combine boolean operations, such as if ($app eq "appname1" || $app eq "appname2" || $app eq "appname3") { ... }
  • Use or for flow control, such as open my $fh, '<', $filename or die "Open failed: $!"
  • Use parentheses when in doubt or if you think the resulting structure might be unclear to a reader (including yourself in six months)
Dave Sherohman
  • 45,363
  • 14
  • 64
  • 102
4

In this case, it doesn't matter, because:

  1. You're using parentheses, which have the highest precedence
  2. eq has a higher precedence than both || and or

Here's what perlop says:

Binary "or" returns the logical disjunction of the two surrounding expressions. It's equivalent to || except for the very low precedence.

Also note that OR (uppercase) is not a valid Perl operator, but or (lowercase) is.

Matt Jacob
  • 6,503
  • 2
  • 24
  • 27
  • Ohk Thanks Matt.. Sorry I didn't mean to use uppercase OR actually i was trying to highlight it in my question – Sampath Feb 10 '17 at 07:09