Anonymous user
Determine if a string is numeric: Difference between revisions
Determine if a string is numeric (view source)
Revision as of 01:35, 15 November 2011
, 12 years ago→{{header|Common Lisp}}: Read-time side effects are suppressed by nulling *read-eval*. Reader can signal error. Memory is not a concern because the input is in a string! So no need for a library.
(→{{header|Common Lisp}}: Read-time side effects are suppressed by nulling *read-eval*. Reader can signal error. Memory is not a concern because the input is in a string! So no need for a library.) |
|||
Line 243:
=={{header|Common Lisp}}==
(numberp (read-from-string string)))</lang>▼
Lisp's reader can be used to read the printed representation of an object from a string, and then this object can be checked whether it is a number.
Read-time evaluation is suppressed by nulling out the special variable <code>*read-eval*</code>. This is necessary if the string came from an untrusted input, allowing an attacker to inject hash-dot syntax to evaluate an arbitrary expression.
A second detail requiring attention is that the reader can signal if it encounters EOF or bad syntax in the middle of an object. The <code>ignore-errors</code> macro catches conditions of type <code>error</code> and turns them into a <code>nil</code> return value, which here conveniently becomes an indicator that the input isn't a number:
<lang lisp>(defun numeric-string-p (string)
(let ((*read-eval* nil))
▲ (ignore-errors (numberp (read-from-string string)))))</lang>
=={{header|D}}==
|