10.4.5  Using strings as commands

The expr command will let you use a string as a command. Given a string that expresses a valid command, expr will convert the string to the command and evaluate it. For example, if you enter

expr("c := 1")

then the variable c will be set to 1. Similarly, if you enter

a := "ifactor(54)"

then

expr(a)

will return

2 * 3^3

which is the same thing as entering ifactor(54) directly.

You can also use expr to convert a string to a number. If a string is simply a number enclosed by quotation marks, then expr will return the number. For example,

expr("123")

will return

123

In particular, the following strings will be converted to the appropriate number.

• A string consisting of the digits 0 through 9 which doesn’t start with 0 will be converted to an integer. For example,
expr("2133")
will return
2133
• A string consisting of the digits 0 through 9 which contains a single decimal point will be converted to a decimal. For example,
expr("123.4")
will return
123.4
• A string consisting of the digits 0 through 9, possibly containing a single decimal point, followed by e and then more digits 0 through 9, will be read as a decimal in exponential notation. For example,
expr("1.23e4")
will return
12300.0
• A string consisting of the digits 0 through 7 which starts with 0 will be read as an integer base 8. For example,
expr("0176")
will return
126
since 176 base 8 equals 126 base 10.
• A string starting with 0x followed by digits 0 through 9 and letters a through f will be read as an integer base 16. For example,
expr("0x2a3f")
will return
10815
since 2a3f base 16 equals 10815 base 10.
• A string starting with 0b followed by digits 0 and 1 will be read as a binary integer. For example,
expr("0b1101")
will return
13
since 1101 base 2 equals 13 base 10.