In perl, both ‘or’ and || mean the same thing. But they act in different ways when used in certain circumstances. For example, lets say we are trying to open a file for read and write operations. It’s always a good idea to handle the IO errors and we do this in the following way:

………………..

$file = shift;

open FILE, $file or die “Couldn’t open the file $file”; #note this

…………………

The second step can also be written in this way:

open FILE, $file || die “Couldn’t open the file $file”; #note this

But when the execution of this program happens, you will never see the message in ‘die’, if you use a || instead of ‘or’. Reason for this is that the || operator has a precedence level higher than that of ‘or’ and since

the ‘open FILE, $file’ returns a value after an attempt to execute, the || is always true and die is never reached.

The actual reason as Martin, one of the commentators puts it,

The actual reason is that the operator precedence for the double pipe is higher than the comma, so perl is resolving the double pipe first, which chooses the first true result of its two parameters, in this case $file and the die statement. As long as $file is a nonempty string it counts as true and always gets returned by the double pipe.

So it is always advisable to use ‘or’ instead of ||. If you want to use ‘||’, you can do it by using the

pen file with parathesis which ensures the precedence of the operators.

open (FILE, $file) || die “Couldn’t open the file $file”;

Share this: Twitter

Facebook

Like this: Like Loading... Related