Perl Style: Don't Overdo `?:'

  • Using ?: for control flow may get you talked about. Better to use an if/else. And seldom if ever nest ?:.

        # BAD
        ($pid = fork) ? waitpid($pid, 0) : exec @ARGS;
    
        # GOOD:
        if ($pid = fork) {
            waitpid($pid, 0);
        } else {
            die "can't fork: $!"    unless defined $pid;
            exec @ARGS;
            die "can't exec @ARGS: $!";
        }
    
  • Best as an expression:

        $State = (param() != 0) ? "Review" : "Initial";
    
        printf "%-25s %s\n", $Date{$url}
                ? (scalar localtime $Date{$url})
                : "<NONE SPECIFIED>",
    

Forward to Never define “TRUE” and “FALSE”
Back to Learn Precedence
Up to index

Copyright © 1998, Tom Christiansen All rights reserved.

Tags

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub

TPRF Gold Sponsor
TPRF Silver Sponsor
TPRF Bronze Sponsor