Uploaded image for project: 'CFEngine Community'
  1. CFEngine Community
  2. CFE-3194

nth() policy function should take negative indices

    XMLWordPrintable

    Details

      Description

      gCurrently (as of 3.12.2, 3.14.0) I can use reverse(), or I can use length() and eval() to calculate the last index position if I want to reference the last element of a list.

      Get the last element of a list using length() and eval()
      bundle agent main {
      
        vars:
              "path" string => "/etc/path/more/something/config.conf";
              "path_parts" slist => string_split( "$(path)", "/", "10");
              "count" int => length("path_parts") ;
              "filename" string => nth("path_parts", format( "%d", eval("$(count)-1", "math", "infix")));
      
        reports:
              "CFEngine $(sys.cf_version)";
              "$(filename)";
      }
      
      R: CFEngine 3.15.0a.732b7da25
      R: config.conf
      Get the last element of a list using reverse()
      bundle agent main {
      
        vars:
              "path" string => "/etc/path/more/something/config.conf";
              "path_parts" slist => reverse(string_split( "$(path)", "/", "10"));
              "filename" string => nth("path_parts", 0 );
      
        reports:
              "CFEngine $(sys.cf_version)";
              "$(filename)";
      }
      
      R: CFEngine 3.15.0a.732b7da25
      R: config.conf

      It would be useful if the nth() policy function could take negative indices, so -1 would be the last one.

      Example getting last element of list using negative index position
      bundle agent main {
      
        vars:
              "path" string => "/etc/path/more/something/config.conf";
              "path_parts" slist => string_split( "$(path)", "/", "10");
              "filename" string => nth("path_parts", -1 );
      
        reports:
              "CFEngine $(sys.cf_version)";
              "$(filename)";
      }
      
      R: CFEngine 3.15.0a.732b7da25
      R: config.conf

      Valid indices would be -length to length - 1, inclusive.

      https://docs.cfengine.com/docs/master/reference-functions-nth.html

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                karlhto Karl Hole Totland
                Reporter:
                olehermanse Ole Herman Schumacher Elgesem
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved:

                  Summary Panel