my %hash = ( a => 1, b => 2, c => 3, d => 4 ); sub foo { my $n = ($_[0]) ? $_[0] : keys %hash; return (keys %hash)[0 .. ($n - 1)]; # return %hash keys from 0 to $n - 1 } my $bar = &foo(); # want to return the number of keys of %hash print "$bar\n";