Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: "open" Best Practices

by Anonymous Monk
on Jul 13, 2019 at 02:18 UTC ( #11102770=note: print w/replies, xml ) Need Help??

in reply to "open" Best Practices

open(my $fh, '<', $filename) || die "$filename: $!";  # ok, but parens required!

Nope, its never "OK", to write code like that is to never get work :)

Common Perl Pitfalls
"or die" versus "|| die"
To || or not to or and why.
Perl Idioms Explained - && and || "Short Circuit" operators
Re: Undefined vs empty string (not length)

Replies are listed 'Best First'.
Re^2: "open" Best Practices
by haukex (Chancellor) on Jul 13, 2019 at 06:11 UTC

    Well, I disagree with the "never", but I did strengthen my warning against it a bit, thanks! BTW, some of those links are of course very relevant, but some of them (e.g. the first two) don't mention the || vs or at all.

      I always use the low precedence and and or operators for flow of control, for example preferring:

      open(my $fh, '<', $file) or die "error opening '$file': $!";
      to the equivalent:
      open(my $fh, '<', $file) || die "error opening '$file': $!";

      while always using && and || inside logical expressions, for example preferring:

      if ($x > 5 || $y < 10) ...
      to the equivalent:
      if ($x > 5 or $y < 10) ...

      When this style is followed consistently, I find the code easier to read and understand at a glance.

      See also Perl Best Practices, Chapter 4, "Values and Expressions", "Don't mix high- and low-precedence booleans" item.

        I agree with everything you've said, and use the operators in the same way myself, with very few exceptions (for example, I might sometimes write if (not ...) instead of unless(...) if it reads better). Consistency is definitely a good thing!

        I was just disagreeing with the "never" part - TIMTOWTDI, and function() || ... is valid Perl and sometimes applicable. In the context of the root node, I explicitly included that form because a newcomer might have seen it in other code, and I think it's good to say that it's not wrong, but also not recommended. Anyway, I've edited the root node further to highlight that even more.

        (What do you think about if( open($fh, '<', $foo) || open($fh, '<', $bar) )? ;-) )

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11102770]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2020-02-28 04:02 GMT
Find Nodes?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?

    Results (122 votes). Check out past polls.