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

Use negative integer positions with nth()

    XMLWordPrintable

    Details

      Description

      Currently (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 convenient if I could more easily grab the elements from a list relative to the end.

      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

      It would then make sense that the valid values for index position used in nth() be 0 to length()-1

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                a10042 Nick Anderson
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved:

                  Summary Panel