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

Re: Implement a key-value deserialization or something similar



On Sep 6, 12:20am, Daniel Shahaf wrote:
} Subject: Re: Implement a key-value deserialization or something similar
}
} Like this:
} 
}     % local -A reply=(mydata 1 otherdata true) 
}     % () { echo ${${(P)7}[otherdata]} } {1..6} reply 
}     true
} 
} Or you could adopt the Perl convention:
} 
}     () {
}       local -A args=( "$argv[@]" )
}     } mydata 1 otherdata true


To more explicitly state what I think what Daniel is means with his
second example, the notion is that you can string key-value pairs
along in the argument list as ordinary arguments as long as you know
how many of the leading arguments are meaningful.  E.g. if your
function takes four arguments, you can extend it like this:

    FnOf4() {
      local -A rest=( $argv[5,-1] )
      argv[5,-1]=()
      print -l "The positional args:" $*
      if [[ -n $rest[foo] ]]; then
        print -l "The foo arg:" $rest[foo]
      fi
    }

    % FnOf4 these are positional and foo bar become rest
    The positional args:
    these
    are
    positional
    and
    The foo arg:
    bar

If you don't know how many arguments will precede the "rest" pairs,
use a flag value such as "--" (that must not appear in the "rest"):

    FnOfN() {
      integer mark=$argv[(I)--]
      local -A rest=( $argv[mark+1,-1] )
      argv[mark,-1]=()
      print -l "The positional args:" $*
      if [[ -n $rest[foo] ]]; then
        print -l "The foo arg:" $rest[foo]
      fi
    } 

    % FnOfN a batch of positional args and -- foo bar become rest

Daniel's first example amounts to setting this up in the caller and then
passing the name of the "rest" hash as $argv[-1], rather than passing
all the key-value pairs as positionals.



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