简体   繁体   中英

In KRL, how do I detect if a variable is an array or hash?

In KRL, I'd like to detect whether a variable is an array or hash so that I know if I need to use the decode or encode operator on it. Is that possible?

I'd like to do something like this:

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

Update The best way to do this is with the typeof() operator. This is new since the answer, but with the early interpretation of variables, the old way listed in the answer will no longer work.

Another useful operator for examining your data is isnull()

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

The only way that I have figured out how to detect the data structure type is by coercing to a string and then checking to see if the resulting pointer string contains the word 'array' or 'hash'.

'One liner'

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

myHashIsHash will be true/1

Example app built to demonstrate concept

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;
    }
  }
}

Example app in action!

替代文字

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM