代码之家  ›  专栏  ›  技术社区  ›  jjmerelo

hash composer的无用用法,或者不能修改不可变的hash?

  •  0
  • jjmerelo  · 技术社区  · 6 年前

    此代码:

    constant %what = { doesn't => 'change' }; 
    %what = { will => "change" } 
    

    Potential difficulties:
    Useless use of hash composer on right side of hash assignment; did you mean := instead?
    

    位置有几乎相同的问题,但错误是不同的。在这种情况下,它是关于不能修改一个不可变的,但是一个Str:

    constant @what = <does not change>;
    @what = <does change> # Cannot modify an immutable Str (does)
    

    0 回复  |  直到 5 年前
        1
  •  7
  •   raiph    4 年前

    此代码:

    constant %what = { doesn't => 'change' }; 
    %what = { will => "change" } 
    

    应该说“不能修改不可变散列”。

    为什么? 你是这么认为的,但使用“应该”这个词时要小心,因为它意味着某些权威这么说,比如规范,或者设计文档,或者某人的常识,等等。


    constant foo ... 绑定 foo 为了某个特定的“价值”。

    如果这个“值”是一个容器,那么

    所以上面的代码改变了包含的元素 在内部

    say %what; # {will => change}
    

    同时,警告消息合法地提到了哈希构造函数的无用使用,并指出:

    did you mean := instead?
    

    constant %what = { doesn't => 'change' }; 
    %what := { will => "change" }
    

    你会得到:

    Cannot use bind operator with this left-hand side
    

    因为,正如已经确定的那样, %what 是编译时常量 永久地 绑定到在编译时创建并初始化的哈希以及该方面--的永久绑定 %什么 在这个程序运行期间不能更改。

    Positional Str :

    constant @what = <does not change>;
    @what = <does change> # Cannot modify an immutable Str (does)
    

    constant 声明绑定,无论您是否编写 = := . 所以常量声明等价于:

    constant %what := { doesn't => 'change' }
    constant @what := <does not change>;
    

    第一行绑定 %什么 { doesn't => 'change' } 这是一个可变的 Hash .

    第二行绑定 @what <does not change> 这是一个不变的 List .

    你可以写:

    constant @what = [<does not change>];
    @what = <does change>;
    say @what; # [does change]
    

    A Scalar 按预期工作。

    不完全是。

    标量

    constant $scalar = 42;
    $scalar = 99; # Cannot assign to an immutable value
    

    记得吗 常数 绑定

    my $scalar := 42;
    $scalar = 99; # Cannot assign to an immutable value
    

    但是 Scalar 与此上下文中的其他容器的工作原理相同:

    constant $scalar = $ = 42;
    $scalar = 99; # OK
    

    (除非你想惹恼别人,否则不要写这样的代码。)

    这是一个LTA错误消息的例子,还是一些容器魔法在起作用?

    这是一个很好的问题,我不打算试着回答。

    推荐文章