在ksh中优雅使用数组 [英] Elegant use of arrays in ksh

查看:168
本文介绍了在ksh中优雅使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ksh中建立某种属性集.

I'm trying build an sort of property set in ksh.

认为最简单的方法是使用数组,但是语法使我丧命.

Thought the easiest way to do so was using arrays but the syntax is killing me.

我想要的是

  1. 在具有名称和属性的配置文件中构建任意大小的数组.
  2. 迭代该列表中的每个项目并获取该属性.

我理论上希望我能做的是

I theory what I wish I could do is something like

MONITORINGSYS={
    SYS1={NAME="GENERATOR" MONITORFUNC="getGeneratorStatus"}
    SYS2={NAME="COOLER" MONITORFUNC="getCoolerStatus"}
}

然后,可以执行以下操作:

Then later on, be able to do something like:

for CURSYS in $MONITORINGSYS
do
    CSYSNAME=$CURSYS.NAME
    CSYSFUNC=$CURSYS.MONITORFUNC

    REPORT="$REPORT\n$CSYSNAME"

    CSYSSTATUS=CSYSFUNC $(date)
    REPORT="$REPORT\t$CSYSSTATUS"
done
echo $REPORT

嗯,那不是真正的编程,但是我想你明白了.

Well, that's not real programming, but I guess you got the point..

我该怎么做?

我并不是说我想使用关联数组.我只是用这种方式使我的问题更清楚...即如果循环类似于:

I do not mean I want to use associative arrays. I only put this way to make my question more clear... I.e. It would not be a problem if the loop was something like:

for CURSYS in $MONITORINGSYS
do
    CSYSNAME=${CURSYS[0]}
    CSYSFUNC=${CURSYS[1]}

    REPORT="$REPORT\n$CSYSNAME"

    CSYSSTATUS=CSYSFUNC $(date)
    REPORT="$REPORT\t$CSYSSTATUS"
done
echo $REPORT

同样适用于配置文件.我只是在寻找一种语法,使它的可读性最低.

Same applies to the config file.. I'm just looking for a syntax that makes it minimally readable.

欢呼

推荐答案

不确定是否要... Kornshell可以处理关联数组和索引数组.

Not exactly sure what you want... Kornshell can handle both associative and indexed arrays.

但是,Kornshell数组是一维的.通过使用$()和eval,可以使用间接方法来模拟二维数组.我在较旧的Perl 4.x和Perl 3.x中做了几次,但这很痛苦.如果需要多维数组,请使用Python或Perl.

However, Kornshell arrays are one dimensional. It might be possible to use indirection to emulate a two dimensional array via the use of $() and eval. I did this a couple of times in the older Perl 4.x and Perl 3.x, but it's a pain. If you want multidimensional arrays, use Python or Perl.

唯一的事情是必须通过typedef命令声明数组:

The only thing is that you must declare arrays via the typedef command:

$ typeset -A foohash    #foohash is an associative array
$ typeset -a foolist    #foolist is an integer indexed array.

也许您的脚本可以看起来像这样

Maybe your script can look something like this

typeset -a sysname
typeset -a sysfunct

sysname[1] = "GENERATOR"
sysname[2] = "COOLER"
sysfunc[1] = "getGeneratorStatus"
sysfunc[2] = "getCoolerStatus"

for CURSYS in {1..2}
do
   CSYSNAME="${sysname[$CURSYS]}"
   CSYSFUNC="${sysfunc[$CURSYS]}"
   REPORT="$REPORT\n$CSYSNAME"
   CSYSSTATUS=$(eval "CSYSFUNC $(date)")
   REPORT="$REPORT\t$CSYSSTATUS"
done
echo $REPORT

这篇关于在ksh中优雅使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆