in reply to Re^2: undef==defined sometimes? (body question)
in thread undef==defined sometimes?
So, if I have a function that returns undef on error, else an array with results, I should assign it to a scalar and and see if it is undef, if not, then hope it's a reference to an array?
Functions can *only* return lists of scalars. That list can contain 0, 1 or more scalars. One way to address your problem is to return an empty list (a list with no elements) on error, but that only works if returning an empty list never occurs on success.
sub func { my ($error) = @_; my @results = ('some', 'values'); # 1 or more values. $error ? () : @results; } for (0..1) { my @results = func($_); print(@results ? "no error (@results)" : 'error', "\n"); }
Another way is to always return exactly one scalar: undef on error or an array reference on success.
sub func { my ($error) = @_; my @results = (); # 0 or more values. $error ? undef : \@results; } for (0..1) { my $results = func($_); print($results ? "no error (@$results)" : 'error', "\n"); }
|
|---|