1. Perl
  2. Operators
  3. here

or operator - OR with low priority

or is one of Perl's logical operators and represents a logical sum. It has the same meaning as ||, but or has a lower operator priority and is generally used between sentences.

Sentence 1 or Sentence 2

With this description, statement 2 is executed when statement 1 returns false.


or as a conditional branch

Taking advantage of these properties, or is often used for conditional branch. For example, if open function fails, write as follows.

open my $fh, '<', $file
  or die qq/Can't open file "$file":$!/;

If the open function succeeds, true is returned and the right-hand side of or is not executed. If the open function fails, undef is returned, so die on the right side is executed and the program ends.

As another example, it is also used with the system function. The system function returns 0 on success, so write:

system(@cmd) == 0
  or die "Can't execute command @cmd";

If you want to write the main processing first and write supplementary error processing later, you can use conditional branch with or.

You can use "and" for conditional branch, but "or" is recommended because it is difficult to read.

# Example rewritten with and
  and die "Can't execute command @cmd";

Related Informatrion