Search code examples
puppet

How to convert string to integer in Puppet


I am trying to convert a time (hour and minute) based string to integer in puppet. It works fine most of the time except when the minute is less than 10, say 08. For those values it throws an exception.

Error: Evaluation Error: The value '08' cannot be converted to Numeric. 

Code used

$minute_string = Timestamp.new.strftime("%M")
#Tried the following and it did not work
#$minute_integer = $minute_string + 0
#Subsequently, attempted the following but it did not work either
$minute_integer = Integer($minute_string)


Solution

  • This looks like issue PUP-6010. That was closed as "won't do", but the comments provide an explanation and workaround.

    In brief, Puppet uses exactly the same rules to convert numeric strings to numbers that it uses to convert numeric literals, and those include that a leading 0x directs interpretation as hexadecimal, and otherwise a leading 0 directs interpretation as octal. Some other languages, such as Ruby and C, have the same convention. But '8' and '9' are not valid octal digits, so the strings '08' and '09' cannot be converted directly to integers by arithmetic operators or the Integer() constructor.

    The recommended solution is to use the scanf function to convert your strings:

    $minute_integer = $minute_string.scanf('%d')[0]
    

    With that format, all digits will be interpreted as decimal, and leading zeroes have no special significance. The function returns an array, of which the [0] of course selects the element at index 0.