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

Re: optimal expansions?





On 2024-04-19 13:40, Lawrence Velázquez wrote:
On Fri, Apr 19, 2024, at 3:22 PM, Ray Andrews wrote:
That's my preferred way to look at 'apt-file search' output (Debian and 
derivatives only of course).  It works fine and I think I understand 
all the expansions and splitting.  One you get used to it the nested 
expansions aren't so scary, just read them from inside out, one step at 
a time and it's easy.  But is it optimal?
How is anyone supposed to answer this question, when you haven't
deigned to mention what your code is supposed to DO?  
I thought I was crystal clear what it is supposed to do: reformat 'apt-file search' output.  The code runs, if you have a Debian derivative fire it up.

You seem to
colorize certain portions of the output by bracketing them with
escape sequences, but which portions, exactly?  What does
"apt-file search" typically output?
I wasn't expecting anyone but Debian users to comment.  Unless there are issues that are apparent just from scanning the code.

You don't check the exit status of "apt-file", so if it happens to
fail for any reason
It's taken care of, just not within that minimal code I showed.

((i=1; i<=$#var; i++ )); do
Since you only ever use "i" in the expansion "${=var[i]}", there
is no reason to use this form of "for".  You can just use the usual

	for x in "$var[@]"; do
Ah!  Now there's a good idea.  I tend to use the above only on  the command line, and the more 'formal' for loop in code -- seems more like C. 
and subsequently "$x" instead of "$var[i]".
Right!  Simpler.
        if [[ "$targ" != "${${=var[i]}[1]}" ]]; then
            targ="${${=var[i]}[1]}"
            var2+="\n${grn}${${=var[i]}[1]}${nrm}" # Copy first word of 
line.
You're doing that thing again, where you use a literal backslash-n
and rely on "print" to interpret it as a newline.  This is bad
practice here because the rest of the string is the arbitrary output
of an external command, which you do not control.  It could easily
contain substrings that are meaningful to "print".
I've come to appreciate the problem!  Now for healthy solutions.
To insert an empty line in your output, just add an empty element
to "var2" in the desired position.

	% var=(a)
	% var+=
	% var+=b
	% typeset -p var
	typeset -a var=( a '' b )
	% print -rC1 -- "$var[@]"
Very good, I'll implement that. 

You should store the result of "${=var[i]}" in a temporary variable
and use that, instead of repeatedly word-splitting the same string
over and over and over.
Right.  Three uses, so a temporary var would earn it's keep. 
    print -l "$var2[@]"
Use "print -r" to prevent "print" from interpreting escape sequences
in its arguments.
... and that meshes with getting rid of the '\n's, yes?

Thanks.  It's the difference between something that merely works, with something that's genuinely well coded.



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