It is not what is executed in the else block, but what is execute after.
if (expression) {
statement (1);
}
else {
statement (2);
}
statement (3);
If statement (1) exits the enclosing scope with return/exit/die/croak, statement (3) is never executed. An if/else is the to do something different based on a condition and then continue doing what is after the construct for all cases. This implies that an else immediately after return/exit/die/croak is always useless.
The original code does it right in the first block:
sub get_filehandle {
my $self = shift;
$self->{file} = shift;
open my $fh, "<", $self->{file}
or die "can't open $self->{file}";
return $fh;
}
Which - when following the wrong method you approve of - would be
sub get_filehandle {
my $self = shift;
$self->{file} = shift;
if (open my $fh, "<", $self->{file}) {
return $fh;
}
else {
die "can't open $self->{file}";
}
}
In my way, the second block should be reduced to
sub get_lines {
my $self = shift;
$self->{file} = shift;
### get the filehandle if we don't already have one
$self->{file_handle} ||= $self->get_filehandle ($self->{file});
return readline ($self->{file_handle}) || undef;
}
That last return is arguable anyway, as the readline method can be a method that legally can return undef, "", and 0 (or any object evaluating as false) indicating that the original code was wrong to start with.
Enjoy, Have FUN! H.Merijn
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.