in reply to Re: Missing $ on loop variable?
in thread Missing $ on loop variable?

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.

Replies are listed 'Best First'.
Re: Re: Re: Missing $ on loop variable?
by Cody Pendant (Prior) on Nov 06, 2003 at 03:23 UTC

    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...)

        Thank you. Your use of "true form" is a good illustration of the principle. I never learned Perl in any formal way as you can see. It's counterintuitive to me, because of the rather strange way I see things I suppose. I blame that bloody awful "Perl for dummies" book.


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