in reply to unless vs. bare block
As a matter of technique, I would write that as:unless (open (QTREES, $file)) { print STDERR "WARNING: get_qtrees() can't open $file for filer $fi +ler!\n"; return; };
First, note the addition of $! in the error message to tell you why the open failed.open my $QTREES, '<', $file or die "WARNING: get_qtrees() can't open ' +$file' for filer $filer!: $!\n";
Rather than returning with a warning, I have used die. Using die is usually preferable to printing a warning and continuing because if the open fails, there is usually little point in continuing (aka fail fast). Note that die throws an exception, so you can always catch that and not exit the program by wrapping the subroutine call in an eval block in the rare case that you want to continue after the open fails. As an alternative, you could first check via -f $file that the file exists and return with a warning if it does not exist and die only if it exists yet the open fails (update: see below and How portable are common $! error codes? for a race-condition-free alternative).
Using lexical file handles (i.e. my $QTREES above) is better style because:
Finally, note that I used the three-argument form of open. As for why the three-argument form of open is preferred, the old two-argument form of open is subject to various security exploits as described at Opening files securely in Perl.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: unless vs. bare block
by JavaFan (Canon) on May 10, 2012 at 05:48 UTC | |
by eyepopslikeamosquito (Archbishop) on May 10, 2012 at 12:02 UTC | |
by JavaFan (Canon) on May 10, 2012 at 20:19 UTC | |
by eyepopslikeamosquito (Archbishop) on May 10, 2012 at 21:15 UTC | |
|
Re^2: unless vs. bare block
by chayashida (Acolyte) on May 10, 2012 at 19:03 UTC | |
by Anonymous Monk on May 11, 2012 at 07:57 UTC | |
|
Re^2: unless vs. bare block
by Anonymous Monk on May 11, 2012 at 07:55 UTC |