Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: how to truncate an array
On Mar 4, 10:04am, Ray Andrews wrote:
}
} This should be dead simple, but I can't figure out how to do it. I have
} an array that can be
} arbitrarily long, and I want to truncate it at 20 elements.
Really an array? Or a string you want to index by character?
array[21,-1]=()
string[21,-1]=''
} setopt POSIX_STRINGS
} string[20]='\0'
No, that inserted a literal backslash zero into the string. You meant
string[21]=$'\0' # Zsh array indices start at 1, not at 0
but even that doesn't do what you intended because it doesn't actually
insert a NUL into the array, it just deletes the 21st character.
Assigning to string slices with subscript syntax causes the string to
act like an array. Also, POSIX_STRINGS means that the string $'...'
ends at the NUL, so $'\0' and $'' and $'\0stuff' are all the same.
(Yes, you have C on the brain. A shell array and a C array are only
loosely related; shell arrays behave more like linked lists.)
Even if it did insert a NUL into the array, the array would't really
be truncated, it's just that this:
} echo "string is now truncated: $string"
would truncate the quoted portion at the NUL and not show you the rest
of the value of $string.
A side-effect of POSIX_STRINGS is that practically speaking the only
way to generate a NUL byte is to read one from an external program.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author