eval不管是在matlab,python,js等语言中,还是在Julia中,都有十分广泛的应用。有些是无法替代的,没有eval,可能还真玩不转。
下面主要讲一下Julia的eval:
一、如何把using放在函数中?
using 是不允许直接放在函数中的,不信你试试。但是,比如,我不同的情况需要调用不同的库,这个时侯如何处理,那么请eval出场是什么必要的事情。否则,真不知如何解决。
比如,一个画出策略出PL的函数:
需要注意的是,变量前加一个$。
function plotStrategy_PL(plotTool,isNeedPlot,dictPL,pl,strategyIOName) #2017-6-4
if isNeedPlot == true
x_axis = sort!(collect(keys(dictPL))) # 日期 为 X轴
y_axis = pl;
strname =string(strategyIOName, "strategy ")
if plotTool =="PyPlot"
eval(:(
begin
using PyPlot
close();clf;
PyPlot.plot($x_axis,$y_axis,color="red",linewidth = 2.0,linestyle ="-") # 变量前加一个$
PyPlot.title($strname) # 变量前加一个$
end))
elseif plotTool =="Winston"
eval(:(
begin
using Winston
Winston.display(Winston.timeplot($x_axis,$y_axis,"r"))
Winston.title($strname)
end))
elseif plotTool =="Gadfly"
#draw(PNG("C:\\Users\\Administrator\\Desktop\\myplot.png", 24cm, 12cm), p)
#show("C:\\Users\\Administrator\\Desktop\\myplot.png")
end
end
end
二、单句
function test()
num =5
str =string("num : $num")
eval(:(println($str)));
end
test()
三、语句段
function test()
num =5
#eval(:(using PyPlot))
str =string("num : $num")
eval(:(begin
println($str)
println(10)
end));
end
test()