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

Re: triviality regarding $# counts



On Wed, Apr 10, 2024, at 8:56 PM, Ray Andrews wrote:
> This works: (Again, this is deep in a function and I have to use eval.)

If eval really is necessary (to be frank, I don't trust your judgment
on this), show us examples that require it, instead of the misleading
Rube Goldberg machines you've been offering.


>     output=$( eval "$@" )   # '$@' will expand to 'print -l $temp' 
> which is the text above.
>     temp=( $( eval $@ ) )    # To get the correct count I need to force 
> an array.
>     linecount=$#temp
>     print -rl -- $output
>     print  $linecount

The count is correct by accident.  Your unquoted command substitution
drops the two empty lines but splits the two lines you say should not
be split.

	% orig='abc
	quote> 
	quote> def ghi
	quote> jkl mno
	quote> 
	quote> pqr'
	% arr=($(print -r -- $orig))
	% typeset -p arr
	typeset -a arr=( abc def ghi jkl mno pqr )


> Various experiments trying to get the correct linecount (23)

There are 25 lines, not 23.


> Different efforts at quoting or using ' ${(@f) ....} ' and various 
> other tricks yield me a linecount of 1, 3, 23, 25, 26, or 738.  And 
> output that deletes the blank lines, or forces everything into one 
> 'line/element'.  Basically I need the array form to to get the line 
> count, but it won't print properly as an array.  Not that it's worth 
> much trouble, but is it possible to get the variable  to print 
> correctly *and* show the count of lines without having to eval it 
> twice?

	% cat foo.zsh
	orig='abc

	def ghi
	jkl mno

	pqr'

	# The sensible way to split on LFs.
	#arr=("${(@f)orig}")

	# A very silly way to split on LFs.  Use double quotes to
	# prevent the result of $(...) from being split and to retain
	# empty words in the result of ${(@)...}.
	arr=("${(@f)$(print -r -- $orig)}")

	typeset -p arr
	print -r -- $#arr

	# Use double-quoted $arr[@] to retain empty elements.  Use
	# "print -C1" to avoid printing an empty line if "arr" is empty.
	print -rC1 -- "$arr[@]"

	% zsh ./foo.zsh
	typeset -a arr=( abc '' 'def ghi' 'jkl mno' '' pqr )
	6
	abc

	def ghi
	jkl mno

	pqr
	%


> ... as it is, it seems that '$#' never counts the lines of output as it 
> actually prints.

You both populate and print your array incorrectly.  For the umpteenth
time, you should use "typeset -p" to inspect your variables' values.


-- 
vq




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