-
Type:
Task
-
Status: Done
-
Priority:
Medium
-
Resolution: Fixed
-
Affects Version/s: None
-
Fix Version/s: 3.15.0
-
Component/s: Built-in functions, function: nth()
-
Labels:
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