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

Re: sorting/uniq-ing an array?

On Aug 9,  2:56am, Sweth Chandramouli wrote:
: Subject: sorting/uniq-ing an array?
: i've come up with a way
: to remove redundant entries from an array (the appropriate part of
: my .zshrc is at the end of this message), but it's very slow
: 	is there a faster way to do this?


typeset -U ports

but the completion code makes its internal list of completions unique,
so it doesn't really help to remove the redundant entries from arrays
in advance when using them only for completion.

: 	(as always, of course, comments on style are also appreciated.
: i'm fairly certain that i still don't understand when ${= is needed
: and when it isn't, so i just tend to use it everywhere that splitting
: might be needed.  did i do it right here?)

You almost never need ${=...} when the "..." refers to an array.  Using
${=...} on an array causes the individual elements of the array to be
split into words, which is not very often what is wanted.  So no, you
didn't do it right here:

: portnames=("${${${(f)$(</etc/services)}:#\#*}%%[        ]*}")
: portnums=("${${${${${(f)$(</etc/services)}:#\#*}%%/*}##*        }##* }")
: ports=(${=portnums} ${=portnames})

However, you're over-processing.  You have both the port numbers and names
at one point during the portnums= computation, but then you throw the names
away.  Keep them:


(Note that there I used ${=...} to re-split the ${(f)...} array of lines,
so sometimes that _is_ what you want.  I did say _almost_ never.)

: for i in $ports ; do
:    unset append;
:    for b in ${=tmpvar} ; do
:       if [[ $i == $b ]] ; then
:          append='false';
:       fi;
:    done;
:    if [[ -z $append ]] ; then
:       tmpvar=($tmpvar $i);
:    fi;
: done;

You probably want to be sure that $tmpvar doesn't already have a value
at the time you start any kind of loop like that.  Also, zsh (and most
other shells) has multi-level loop break/continue, so you can restart
the outer loop without setting/testing $append from the inner loop:

for i in $ports ; do
  for b in $tmpvar ; do
    [[ $i == $b ]] && continue 2
  tmpvar=($tmpvar $i)

Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

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