在KRL中,如何检测变量是数组还是哈希?

时间:2011-01-18 17:36:30

标签: krl

在KRL中,我想检测变量是数组还是散列,以便我知道是否需要在其上使用解码或编码运算符。这可能吗?

我想做这样的事情:

 my_var = var.is_array => var.decode() | my_var

2 个答案:

答案 0 :(得分:3)

<强>更新 执行此操作的最佳方法是使用 typeof()运算符。这是答案以来的新内容,但随着变量的早期解释,答案中列出的旧方式将不再有效。

检查数据的另一个有用的运算符是 isnull()

myHash.typeof() => "hash"
myArray.typeof() => "array"
...

答案 1 :(得分:2)

我弄清楚如何检测数据结构类型的唯一方法是强制转换为字符串,然后检查生成的指针字符串是否包含单词“array”或“hash”。

'One liner'

myHashIsHash = "#{myHash}".match(re/hash/gi);

myHashIsHash将为true / 1

为展示概念而构建的示例应用

ruleset a60x547 {
  meta {
    name "detect-array-or-hash"
    description <<
      detect-array-or-hash
    >>
    author "Mike Grace"
    logging on
  }

  global {
    myHash = {
      "asking":"Mike Farmer",
      "question":"detect type"
    };
    myArray = [0,1,2,3];
  }

  rule detect_types {
    select when pageview ".*"
    pre {
      myHashIsArray = "#{myHash}".match(re/array/gi);
      myHashIsHash = "#{myHash}".match(re/hash/gi);
      myArrayIsArray = "#{myArray}".match(re/array/gi);
      myArrayIsHash = "#{myArray}".match(re/hash/gi);

      hashAsString = "#{myHash}";
      arrayAsString = "#{myArray}";
    }
    {
      notify("hash as string",hashAsString) with sticky = true;
      notify("array as string",arrayAsString) with sticky = true;

      notify("hash is array",myHashIsArray) with sticky = true;
      notify("hash is hash",myHashIsHash) with sticky = true;
      notify("array is array",myArrayIsArray) with sticky = true;
      notify("array is hash",myArrayIsHash) with sticky = true;
    }
  }
}

示例应用在运行中!

alt text