You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

COBOL中直接使用内置函数后字段比较不符预期的原因咨询

COBOL函数直接比较异常的原因分析

问题场景

在COBOL开发中,使用UPPER-CASE和TRIM内置函数处理字段后直接比较,出现不符合预期的结果:明明不相等的内容(处理后的WERT1与WERT1 X)被判定为相等,但将函数结果存入固定长度字段后再比较,结果符合预期。

示例程序

program-id. tintr.
       data division.
       working-storage section.

       01  ws-feld1   pic x(10).
       01  ws-feld2   pic x(10).
       01  ws-feld3   pic x(10).
       01  ws-feld4   pic x(10).

       procedure division.

           move "Wert1 " to ws-feld1
           move "wert1 x" to ws-feld2
      *
           display "<" function upper-case(ws-feld1) ">"
           display "<" function upper-case(ws-feld2) ">"
      *
           display "<" function trim(ws-feld1) ">"
           display "<" function trim(ws-feld2) ">"
      *
           display "<" function upper-case
           (function trim(ws-feld1)) ">"
           display "<" function upper-case
           (function trim (ws-feld2)) ">"
      * Compare WS-Feld1/WS-Feld2
           if ws-feld1 = ws-feld2
           then
              display " felder1-2 identical"
           else
              display " felder1-2 not identical"
           end-if
      * Compare Functions uppercase/Trim
           if function upper-case
           (function trim(ws-feld1))
           =
            function upper-case
           (function trim(ws-feld2))
           then
              display " felder1-2/function identical"
           else
              display " felder1-2/function not identical"
           end-if
      * moving result of functions into field
           move function upper-case
           (function trim(ws-feld1))
           to ws-feld3
           
           move function upper-case
           (function trim(ws-feld2))
           to ws-feld4
      * Compare WS-Feld3/WS-Feld4
           if ws-feld3 = ws-feld4
           then
              display " felder3-4 identical"
           else
              display " felder3-4 not identical"
           end-if
      *

           stop run.

      *

运行结果

<WERT1     >
<WERT1 X   >
<Wert1>
<wert1 x>
<WERT1>
<WERT1 X>
felder1-2 not identical
felder1-2/function identical
felder3-4 not identical

异常原因

这个问题的核心是COBOL对可变长度字符串的比较规则和编译器对函数返回值的处理逻辑:

  • TRIM和UPPER-CASE函数返回的是可变长度字符项,其逻辑长度等于处理后的实际有效字符数(比如ws-feld1处理后为5位,ws-feld2处理后为7位)。
  • 当直接在IF语句中比较两个可变长度字符项时,COBOL仅比较到两个字符串中较短的逻辑长度为止。如果该范围内的所有字符匹配,就会判定两个字符串相等。你的例子中,两个函数结果的前5位都是WERT1,因此被误判为相等。
  • 当将函数结果存入固定长度字段(如ws-feld3/ws-feld4,长度10位)时,可变长度字符串会被自动填充空格至字段长度,此时比较的是完整的固定长度字段,会检查所有10位字符,自然能发现ws-feld4中第7位的X与ws-feld3的空格差异,得到正确结果。

内容的提问来源于stack exchange,提问作者user30144283

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:57:02