Appropriate way to return an arrayref from a sub with optional sorting in Perl version 5.20
Solution 1:
If you insist on sorting out the sorting business in the return
statement itself can use a ternary
return $sort ? [ sort @res ] : \@res;
This may be all well and clear enough in simple cases.
However, I find it clearer to first deal with cases and options and then return the result
@res = sort @res if $sort;
if ($mode == 1) { ... } # modes given in the question do nearly the same,
elsif ($mode == 2) { ... } # but imagine different processing based on value
...
return \@res;
Also, sorting in place should be a little more efficient.
If this were about efficiency then you'd want to benchmark different approaches, and under realistic circumstances. For one, it may all get blown out of the water by reading a large directory, when one may not be able to tell any performance difference in how exactly the return is constructed.
So I'd go for clarity, until it is clearly seen that the choice does affect performance.