techie411 has asked for the wisdom of the Perl Monks concerning the following question:

Hi There:
How would I take the first value of the key?

For instance:
foreach $key (sort(keys %in)) { print MAIL "\t", $key, " = \t", $in{$key}, "\n"; } close MAIL;

I want to take the first key value only. How would I go about doing it? Thanks in advance!

Replies are listed 'Best First'.
Re: First Value in hash
by Corion (Patriarch) on Jan 08, 2008 at 09:21 UTC

    "How do I make a single step?"

    "You start walking and then stop after the first step."

    foreach $key (sort(keys %in)) { print MAIL "\t", $key, " = \t", $in{$key}, "\n"; last; } close MAIL;

    Or, as an approach that is a bit more verbose yet without the loop:

    my @keys = sort keys %in; print MAIL "\t", $key[0], " = \t", $in{$key[0]}, "\n";

    Or, as an approach that is a bit more transparent and doesn't use the array:

    (my $first) = sort keys %in; print MAIL "\t", $key, " = \t", $in{$key}, "\n";
Re: First Value in hash
by ysth (Canon) on Jan 08, 2008 at 09:59 UTC
Re: First Value in hash
by bingos (Vicar) on Jan 08, 2008 at 09:20 UTC

    TIMTOWTDI, but perhaps:

    my $key = ( sort keys %in )[0];
Re: First Value in hash (List::Util::minstr())
by lodin (Hermit) on Jan 08, 2008 at 11:18 UTC

    Instead of sorting the keys, which is unnecessary work, you can use List::Util's minstr subroutine.

    use List::Util 'minstr'; my $first_key = minstr(keys %in);

    lodin

Re: First Value in hash
by apl (Monsignor) on Jan 08, 2008 at 10:52 UTC
    My answer is, essentially, "what ysth said".

    The purpose of a hash is to provide fast access to a specific key, rather to store information in a sequential order.

    You can always store the order an item was entered, and scan for it later. That is:

    $in{$key}{rank} = $nthElement++;

    Followed by
    foreach $key (sort(keys %in)) { print MAIL "\t", $key, " = \t", $in{$key}, "\n" if $in{$key}{rank} == 0; }