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

Re: Confused about splitting



Anssi Saari wrote on Sun, Mar 31, 2019 at 12:06:16 +0300:
> foofunc2 () {
⋮
> 	setopt shwordsplit

This should have been «setopt localoptions shwordsplit».

⋮
> }

> But what if I don't want to set shwordsplit? I came up with
> 
> foofunc3 () {
> 	if [[ $# -ge 1 ]]
> 	then
> 		if=$1 
> 	else
> 		if=eno1
> 	fi
> 	while read g
> 	do
> 	    if [[ $g =~ $if ]]
> 	    then
> 		first=${=g}
> 		break
> 	    fi
> 	done < /proc/net/dev
> 
> 	echo $first
> 	echo length of first is $#first
> }
> 
> But this splits each character into an array element. I don't understand
> this behavior at all. As I understand it, = in the assignment to $first
> is supposed to turn shwordsplit on temporarily but it really doesn't
> seem to. IFS is not set so field separator should be default, meaning
> whitespace.

«${=g}» does split the value of the parameter 'g'; you can see that with
«printf '[%s]' ${=g}».  Then, that intermediate result — an array of words — is
assigned to the parameter 'first' scalarly, so the value of $first is set to be
the words of the array joined by spaces as a single string.  That's why «echo
$first» has the right output.  The «echo $#first» line prints the length of the
string "$first" in characters, because that's what the «$#foo» syntax does when
foo is a scalar.

The fix is to add back the parentheses to make the assignment an array
assignment: «first=( ${=g} )».

Furthermore, note that if $first had been an array of one-character strings,
the output of the first 'echo' would have been incorrect: compare «echo $foo»
(echos a string) and «echo ${(s::)foo}» (echos an array of one-character
strings).

Cheers,

Daniel



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