At 18:25 2001.08.12, Birgit Kellner wrote:
>Hm, what's the shortest way to do this: I have a hash where one, and only one, key 
>begins with a number, I don't know its value and want to assign this value to a 
>variable.
>
>If I were to do a foreach loop, I'd do this (presuming that %hash is already defined):
>
>foreach my $key(keys %hash) {
>        if ($key =~ /^\d/) {push (@keys, $key); }
>}
>
>But since I know there will only be one key where this condition is true, looping and 
>creating an array seems like a waste.
>
>
>Birgit Kellner

How about :

foreach my $key (sort keys %hash)
{
  if ($key =~ /^\d/) {
    push (@keys, $key); # Put the key in the keys list 
    last;               # Exit the loop, do not proccess the rest of %hash.
  }
}

Since sorting a list is faster than processing each element of it and since numbers 
are sorted before letters, you should find your number very fast.

If you are looking for other type of data, you could make yourself a special sort.

You could also use the grep command and generate a list with only the keys that match 
the regex. As in
  
  my $key = (grep /^d/, (keys %hash))[0]; # Find one key begining with a number.
  push (@keys, $key);                     # Put the key in the keys list.

Hope it helps.


-----------------------------------------------------------
Éric Beaudoin                <mailto:[EMAIL PROTECTED]>


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to