Elixir交互式Shell: 4. 处理文件和脚本

Elixir交互式Shell: 1. 运行时系统标记
Elixir交互式Shell: 2. 常用命令
Elixir交互式Shell: 3. 创建本地和远程Shell
Elixir交互式Shell: 4. 处理文件和脚本
Elixir交互式Shell: 5. 配置IEx

这是IEx系列五部分中的第四部分, 在这一部分中, 我们将说明如何设置在IEx中处理文件和脚本

导入文件

输入h import_file查看文档

iex(remote@localhost)2> h import_file
Evaluates the contents of the file at path as if it were directly typed into the shell.
...

import_file的作用是, 对导入的文件进行求值, 就像直接在shell中输入一样, 和复制一个文件的内容并粘贴到IEx Shell中的效果一模一样

本地变量

有如下test1.exs文件:

fred = :fred
defmodule Hello do
  def foo do
    "This is foo"
  end
end
IO.puts fred
iex(1)> import_file "test1.exs"
fred
:ok
iex(2)> fred
:fred
iex(3)> Hello.foo
"This is foo"
iex(4)> 

因为import_file是在IEx 导入的上下文进行求值

test2.exs

fred = :fred
defmodule Hello do
  def foo do
    "This is foo"
  end
end

x10 = x * 10
# 现在 `x` 还没有定义

定义x, 并导入test2.exs

iex(1)> x = 5                  
5
iex(2)> import_file
import_file/2    
iex(2)> import_file "test2.exs"
50
iex(3)> x10
50

我们看到 x10 = x * 10的到了正确的结果 50

IEX -S 搜索

  • iex -s mix - 如果在一个mix项目中, 查找本地mix.exs

否则

  • 文件名必须包括扩展名

  • 文件必须可执行

  • 文件必须在路径中, 除非提供绝对路径

IEx.pry

IEx.pry 给我们提供了一个调试Elixir代码的能力. 我们能够在访问 IEx.pry插入位置的作用域内的变量值. IEx.pry让IEx进入了IEx.pry插入位置的作用域, 因此该作用域外部的变量, 在IEx中不能再访问了, 下面的例子说明了IEx.pry是如何工作的.

首先创建一个pry.exs文件

cat > pry.exs <<EOF
require IEx

fred = :fred
defmodule Hello do
  def foo do
    x = 5
    IEx.pry
    IO.puts "x is #{x}"
  end
end
EOF
iex(1)> bar = :bar
:bar
iex(2)> import_file "pry.exs"
{:module, Hello,
 <<70, 79, 82, 49, 0, 0, 15, 24, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 126, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>,
 {:foo, 0}}
iex(3)> bar
:bar
iex(4)> fred
:fred
iex(5)> Hello.foo   # 进入函数作用域
Request to pry #PID<0.62.0> at iex:7
Allow? [Yn] Y

Interactive Elixir (1.2.1) - press Ctrl+C to exit (type h() ENTER for help)
pry(1)> bar  # 函数外部的变量不再可用
** (UndefinedFunctionError) undefined function :erl_eval.bar/0
    
pry(1)> fred
** (UndefinedFunctionError) undefined function :erl_eval.fred/0
    
pry(1)> x   # 显示foo函数作用域中的x值
5
pry(2)> x = 4
4
pry(3)> respawn # 结束`IEx.pry`会话返回上层IEx Shell

Interactive Elixir (1.2.1) - press Ctrl+C to exit (type h() ENTER for help)
x is 5  # 执行`IEx.pry`插入点后的代码, x的值没发生编号
:ok 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值