in reply to List context or not?

If you want the subroutine to be sensitive to whether it's being called in a scalar context or not, use wantarray.
sub foo { my $n = $_[0] ? $_[0] : keys %hash; return wantarray() ? (keys %hash)[0..($n-1)] : $n }
I assume your example is contrived. If not, you might check to see whether there are at least $_[0] keys.