3

当我的表单帖子中有整数和浮点数并在我有梁文件的 ebin 文件中接收这些时,我遇到了问题。希望可以有人帮帮我。

npower.yaws

   <erl>
kv(K,L) ->
{value, {K, V}} = lists:keysearch(K,1,L), V.        
out(A) ->
L = yaws_api:parse_post(A),
N = kv("number", L),
    npower62:math3(N).
    </erl>

npower62.erl 编译成束文件
-module(npower62)。
-导出([math3/1])。

math3( [N] ) ->
Number = N,
Nsquare = Number * Number,
{html, io_lib:format("square of ~c = ~w", [N, Nsquare])}。

给我 3 = 2601
的平方而不是
3 = 9的平方
我尝试使用 Number = list_to_integer(atom_to_list(N)) (不起作用)
我尝试使用 Number = list_to_float(atom_to_list(N)) (不起作用)
我尝试使用 Number = list_to_integer(N) (不起作用)

4

1 回答 1

0

首先,您可以缩小math3/1函数接受的范围:

-module(npower62). 
-export([math3/1]). 

math3(N) when is_number(N) -> 
  N2 = N * N,
  io_lib:format("square of ~p = ~p", [N, N2]).

请注意,我们已经对函数进行了相当多的重写。它不再接受列表,但N只接受任何数字。此外,您传递给的格式字符串io_lib:format/2完全关闭,请参阅man -erl io.

我们现在可以攻击 yaws 代码:

<erl>
  kv(K,L) ->
      proplists:get_value(K, L, none).

  out(A) ->
    L = yaws_api:parse_post(A),
    N = kv("number", L),
    none =/= N, %% Assert we actually got a value from the kv lookup

    %% Insert type mangling of N here so N is converted into an Integer I
    %% perhaps I = list_to_integer(N) will do. I don't know what type parse_post/1
    %% returns.

    {html, npower62:math3(I)}
</erl>

请注意,您的kv/2函数可以使用 proplists 查找函数编写。在您的代码变体中,return fromkv/2是在您的版本{value, {K, V}}永远不会正确的值math3/1proplists:get_value/3仅返回V部分。另请注意,我将 {html, ...} 提升到了这个级别。让 npower62 处理它是不好的风格,因为它不应该知道它是从 yaws 内部调用的事实。

我的猜测是你需要调用 list_to_integer(N)。解决这个问题的最简单方法是调用error_logger:info_report([{v, N}])并在 shell 或日志文件中查找 INFO REPORT 并查看术语 N 是什么。

TL;DR:问题在于您的价值观并非在所有地方都匹配。因此,您将面临 yaws 可能会捕获、记录然后幸存下来的功能的无数崩溃。然后,这会让您感到困惑。

另外,npower62:math3/1erlshell 测试你的函数函数。这样一来,您就会从一开始就发现它是错误的,从而减少了您的困惑。

于 2010-12-07T01:28:45.337 回答