Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

First Value in hash

by techie411 (Acolyte)
on Jan 08, 2008 at 09:16 UTC ( #661035=perlquestion: print w/ replies, xml ) Need Help??
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!

Comment on First Value in hash
Download Code
Replies are listed 'Best First'.
Re: First Value in hash
by Corion (Pope) 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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://661035]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2015-09-05 01:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred temperature scale is:










    Results (151 votes), past polls