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

Re: A bug or improperly formatted script



On Feb 25, 12:34pm, Jim wrote:
}
} While doing a search, unrelated, I found the following on the
} zsh-lovers(1) man page:
} 
} # Count the number of directories on the stack
}   $ print $((${${(z)${(f)"$(dirs -v)"}[-1]}[1]} + 1)) #...
} 
} I was surprised the first time I tried it I got "-2" as the output.
} 
} It would appear as if the original script is returning
} a scalar when the stack only has one entry and an array when the
} stack has 2 or more entries.

Yes, this is a known / traditional behavior, and it somewhat regularly
comes up in examples where a program has been tested only in the "more
than one element" cases.

The problem is that nesting ${${...}} "wants" to treat the inner ${...}
as a scalar, and will do so unless something else forces it to be an
array.  (f) doesn't accomplish that because $(dirs -v) produces only
one line of output with the final newline stripped, so there is nothing
for (f) to split on.  (@) won't accomplish it because it only means
that things that are already arrays should remain so.

So what can be done to force interpretation as an array here?  Unless
someone else has a better solution, the answer is to forcibly assign
the result to an array variable:

print $((${${(z)${(Af)reply::="$(dirs -v)"}[-1]}[1]} + 1))

Once we are expanding ${reply} rather than ${"$(dirs -v")} the array
property is preserved and [-1] remains an array subscript instead of
becoming a scalar string slice.

A follow-up to this is going to zsh-workers.



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