Web Development

Perl binding, or vs. ||

Perl binding

Perl has "||" and "or". While "or" can’t be used in bit operations, either one can be used in logical flow control – but there is an important difference between them. For example, this code doesn’t work properly:

#!/usr/bin/perl
open FILE, "$file" ||  die "Can't open: $! \n";
print "$file open";

If "$file" doesn’t exist, you won’t get the "Can’t open" message. The problem is that the "||" binds tightly and confuses the "open" function. You need to either do:

 open FILE, "$file" or die "Can't open: $! \n";

(because or binds less tightly than ||) or

 open(FILE, "$file") || die "Can't open: $! \n";

(because the parens contain the open function)

Generally speaking it’s a very good idea for new Perl folk to use "or" rather than "||" in conditional flow tests, and to use parens for functions. So (following both rules), I’d recommend getting used to writing that like this:

 open(FILE, "$file") or die "Can't open: $! \n";

at least until you are very clear on what each of these does.

About the author

Written by Tony Lawrence.

If you found this post useful you may also want to check these out:

  1. Perl Input
  2. Cultured Perl: Reading and Writing Excel Files with Perl
  3. Perl Range Operator
  4. Cultured Perl: Automating UNIX System Administration with Perl
  5. Cultured Perl: Genetic Algorithms Applied with Perl
  6. Perl Sorting