icon Top 9 categories map      RocketAware > Perl >

C-style Logical Or

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

C-style Logical Or

Binary ``||'' performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

The || and && operators differ from C's in that, rather than returning 0 or 1, they return the last value evaluated. Thus, a reasonably portable way to find out the home directory (assuming it's not ``0'') might be:

    $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
        (getpwuid($<))[7] || die "You're homeless!\n";

As more readable alternatives to && and ||, Perl provides ``and'' and ``or'' operators (see below). The short-circuit behavior is identical. The precedence of ``and'' and ``or'' is much lower, however, so that you can safely use them after a list operator without the need for parentheses:

    unlink "alpha", "beta", "gamma"
            or gripe(), next LINE;

With the C-style operators that would have been written like this:

    unlink("alpha", "beta", "gamma")
            || (gripe(), next LINE);


Source: Perl operators and precedence
Copyright: Larry Wall, et al.
Next: Range Operator

Previous: C-style Logical And



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: Binary math




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlop/C_style_Logical_Or.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments