Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: scope of variables in loops



"Joey Mingrone" wrote:
> Unlike bash, parameters that are set in loops on the command line
> stick around.  It's not a big deal once you figure out what's going
> on, but the code below can cause some head-scratching.  Is this
> intended?  Is it controllable (is there a way to turn it off)?
>
> zsh 4.3.6 (i386-portbld-freebsd7.0)% for ((x=0; x<=10; x++)) do echo "$x"; do
...
> zsh 4.3.6 (i386-portbld-freebsd7.0)% for x in `ls *`; do echo $x; done
> zsh: bad floating point constant

There's nothing to turn off, as such, but as you say it does cause
head-scratching.

If you haven't declared a variable, and its first use is in a
mathematical context, then it's implicitly type, in this case as an
integer, as if you'd typed "integer x" before the first loop.  (Yes,
even despite the message about the bad floating point constant: that's
probably because it encountered a dot when looking at what it thought
was a formula, even before it tried to turn the formula into an
integer.)  So when you try to use it as a scalar the shell tells you
about it.

You can avoid this by explicitly typing the x as a scalar with "typeset
x" before the first use.  If it's become an integer you can use "typeset
+i x": that's a better bet than just unsetting it, because it means it
won't implicitly become an integer again.  It'll still be able to hold
integers, except it'll hold them as the string you see rather than in
the internal integer format.

By the way, you should write "for x in *", not "for x in `ls *`", unless
you're really relying on obscure effects such as getting names of
directories with a trailing colon together with the directory contents
or having the file names split on spaces.  (Presumably you're not
expecting such problems but it's a good habit to get into anyway.)
There are probably better ways of getting any special effects in zsh,
too.

-- 
Peter Stephenson <p.w.stephenson@xxxxxxxxxxxx>
Web page now at http://homepage.ntlworld.com/p.w.stephenson/



Messages sorted by: Reverse Date, Date, Thread, Author