anirudh bhaskar
anirudh bhaskar

Reputation: 29

Can we use user input to assign variables in Julia?

ans=readline(stdin)

function g(n)
if ans==a
return 1
else
return n
end

This is my code but the readline function only takes strings and i want it to take an expression which i can use in my function. What i want is to assign an expression (a) for variable ans.

Upvotes: 2

Views: 276

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

You could try something like this:

julia> function check(x)
           ans = readline()
           val=Main.eval(Meta.parse(ans))
           println("val == $x :", val==x)
       end;

julia> check(5)
2+3
val == 5 :true

Remarks:

  1. Your functions should not reference global variables (like ans in your example) - if you need to get the value of ans - pass it as parameter.
  2. Parsing the expression is unsafe - a user might want for an example use this functionality to delete your data. Use with care! In some scenarios you might want for an example to use regular expressions to validate user's input.

Upvotes: 1

Related Questions