in reply to Missing $ on loop variable?

perl -e'%hash=(1,"a",2,"b",3,"c"); foreach keys ( %hash ) { print }' Missing $ on loop variable at -e line 1. perl -e'%hash=(1,"a",2,"b",3,"c"); foreach ( %hash ) { print }' 1a3c2b perl -e'%hash=(1,"a",2,"b",3,"c"); foreach $keys ( %hash ) { print $ke +ys }' 1a3c2b perl -e'%hash=(1,"a",2,"b",3,"c"); foreach ( keys %hash) { print }' 132

Nothing wrong with ( %hash ), but keys looks like a loop variable in that context (as hardburn describes well).

Warnings and error messages are usually complaining about the right thing (at least in some way). If you think its wrong, read it again. I speak from personal experience of being too ready to disbelieve error codes. More often than not the simplest reading is the right one.

Replies are listed 'Best First'.
Re: Re: Missing $ on loop variable?
by Anonymous Monk on Nov 06, 2003 at 02:01 UTC
    Particularly true because in other languages (namely Bourne shell), you leave off the $ on loop variables, and many Perl newcomers over the years have been confused by that.

      Thanks all of you, particularly Schemer for a quick and straightforward answer, and Anonymous Monk for the explanation of why it might be a useful error message for someone coming from a shell scripting background.

      I still think perhaps "something between foreach and a list which is not a variable" would be a better error message though. I saw this construct as foreach, followed by something that I know returns a list, keys(%hashname), where's the error? It's kind of counter-intuitive for me at least.



      ($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss') =~y~b-v~a-z~s; print

        Its not counterintuitive.

        From the perlsyn documentation:

        The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) If VAR is omitted, $_ is set to each value.

        You got it backwards; its "true form" is foreach, followed by a variable, followed by a list with the special case that not writing the var makes it $_ . Also, to avoid that kind of problems, is highly recomended that you put the list inside (), so you know is a list.

        Jesús Couto F. (now, where did I put my password for this site...)