Hello adriang,

I realise your code snippet is just for illustration; still, it may be instructive to note its various problems:

  1. while ( my $key=keys(%hash) {

    Compile error: the second closing parenthesis is missing.

  2. my $key=keys(%hash)

    Logic error: in scalar context the keys function returns the number of keys in the hash, not the keys themselves. You need a for loop here:

    for my $key (keys %hash) {
  3. keys %hash

    Logic error: since you want to exit the loop when a certain key is reached, the behaviour of the code depends on the order in which the keys are returned; but this order is “apparently random” (keys). To get deterministic behaviour, you need to sort the keys. For example:

    for my $key (sort keys %hash) {
  4. }  $hash{$key}=$verb;

    Compile error: if you’re running under use strict; (and you should be!), you will see this error message:

    Global symbol "$key" requires explicit package name at ...

    You could fix this1 by declaring my $key; before the loop, but it’s better style to restrict the scope of this lexical variable:

    for my $key (sort keys %hash) { if ($key eq $verb) { $hash{$key} = $verb; last; } }

Update (Aug 23):
1That is, you could fix the error message. But the code still wouldn’t work correctly, because $key is a temporary alias within the foreach loop (see “alias” in perlglossary), and it reverts to its pre-loop value when the loop ends.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: while loop question by Athanasius
in thread while loop question by adriang

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.