AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79492046
Accepted
An5Drama
An5Drama
Asked: 2025-03-07 18:57:03 +0800 CST2025-03-07 18:57:03 +0800 CST 2025-03-07 18:57:03 +0800 CST

非 C 风格 for 循环中“my”变量的作用域

  • 772

最近尝试获取一个“获取匹配括号的索引”的算法。虽然 perl 语言有些问题,但我能理解该算法的含义。

perl 语法并不晦涩,并且可以通过man perl...文档获得很多信息。

my但我对循环行为有点困惑for。man perlsyn说:

如果变量前面带有关键字“my”,则该变量具有词法作用域,因此仅在循环内可见。否则,该变量隐式地位于循环中,并在退出循环时恢复其以前的值。如果变量之前用“my”声明,则它使用该变量而不是全局变量,但它仍然位于循环中。这种隐式本地化仅发生在非 C 样式循环中。

我知道“非 C 风格循环”是指那些不像的循环for (...;...;...){...}。

第一句话可以通过以下方式显示,类似于文档中显示的示例:

$i = 'samba';
# If the variable is preceded with the keyword "my", then it is lexically scoped, and is therefore visible only within the loop.
for (my $i = 1; $i <= 4; $i++) {
  print "$i\n";
}
print "$i\n";
# 1
# 2
# 3
# 4
# samba

但我不明白第二点是什么意思:

$inner = 'samba';
for ($i = 1; $i <= 4; $i++) {
  $inner = $i + 1;
}
print "inner: $inner\n";
# inner: 5

这里所谓的“本地”var$inner似乎修改了外部的var,并且“以前的值”'samba'无法“恢复”。

第三,我们可以对上面的例子做一些小的调整:

$inner = 'samba';
for ($i = 1; $i <= 4; $i++) {
  my $inner = $i + 1;
}
print "inner: $inner\n";
# inner: samba

这对于“而不是全局的”来说是可以正常工作的。

如何理解循环my中的行为for,尤其是上面引用中的第二句?


后续澄清 choroba 的回答提示:当使用正确的“非 C 风格循环”时,第 1 句和第 2 句似乎意味着是否my用于 var 具有相同的效果。但事实并非如此。

sub foo { print "foo: $x\n"; }

$x = 7;
for $x (1 .. 3) {  # Implicit localisation happens here.
  print "$x\n";
  print "global $::x\n";  # Prints 1 .. 3 correspondingly.
  foo(); # Prints 1 .. 3 correspondingly.
}
print $x;  # Prints 7.

$x = 7;
for my $x (1 .. 3) {  # Implicit localisation happens here.
  print "$x\n";
  print "global $::x\n";  # Always prints 7.
  foo(); # Always prints 7.
}
print $x;  # Prints 7.

这只是和之间的区别localmy,仅意味着动态范围与词法范围,正如那里的最佳答案所示,这也在文档中有所说明。

局部变量只是为全局变量(即包变量)赋予临时值。它不会创建局部变量。这称为动态作用域。词汇作用域由我的...完成。

第三个句子示例可以更新:

$i = 'former';
my $i = 'samba';
for $i (1 .. 4) {
  print "$i\n";
}
# > still localized to the loop
# i.e. uses the outside variable value but maybe there are more than one choices. The doc says to choose "my $i = 'samba';".
print "$i\n"; # not use 'former'
# 1
# 2
# 3
# 4
# samba

针对 ikegami 的回答的后续问题:

如果我们添加:

my $x = 7;
for $x (1 .. 3) {  # Implicit localisation happens here.
  print "$x\n";
  print "global $::x\n"; # Prints nothing for $::x.
  foo(); # Prints nothing for $x.
}
print $x;  # Prints 7.

对于上面的sub foo { print "foo: $x\n"; } ...例子,后者$::x 也不能访问后者定义的全局变量$x = 7;。恕我直言,my创建一个新的变量不应该影响那个全局变量。

但是如果我们将后者的 var 定义为our $x = 7;文档中所说的“包(即全​​局)变量的词汇别名”。那么一切都会像以前一样工作。这是什么原因呢?

for-loop
  • 2 2 个回答
  • 104 Views

2 个回答

  • Voted
  1. choroba
    2025-03-07T19:02:03+08:002025-03-07T19:02:03+08:00

    非 C风格是

    for my $x (1 .. 10) {
    

    它的工作原理如下:

    my $x = 7;
    for $x (1 .. 3) {  # Implicit localisation happens here.
        print $x;
    }
    print $x;  # Prints 7.
    

    文档没有讨论其他非循环变量。变量范围的一般规则适用于它们。

    另外,养成使用strict的习惯。它使变量范围更加明确和可控。

    要本地化全局变量,请使用local。

    • 7
  2. Best Answer
    ikegami
    2025-03-08T00:55:02+08:002025-03-08T00:55:02+08:00

    首先我要说的是,除了使用时,你总是想要。my$_


    如果变量前面有关键字“my”,那么它就是词汇范围的,因此仅在循环内可见。

    演示:

    our $x = 9;
    
    sub f { say $x; }         # Accesses outer `$x`
    
    for my $x ( 1 .. 3 ) {    # Creates a new `$x` scoped to the loop
       say $x;                # Accesses loop `$x`
       f();
    }
    
    say $x;                   # Accesses outer `$x`
    

    输出:

    1
    9
    2
    9
    3
    9
    9
    

    否则,该变量隐式地局部于循环,并在退出循环时恢复其原来的值。

    演示:

    our $x = 9;
    
    sub f { say $x; }         # Accesses the only `$x`
    
    for $x ( 1 .. 3 ) {       # Backs up and restores the SV associated with `$x`.
       say $x;                # Accesses the only `$x`
       f();
    }
    
    say $x;                   # Accesses the only `$x`
    

    输出:

    1
    1
    2
    2
    3
    3
    9
    

    换句话说,该代码在功能上等同于以下内容:

    use experimental qw( declared_refs defer refaliasing );
    
    our $x = 9;
    
    sub f { say $x; }              # Accesses the only `$x`.
    
    {
       my \$backup = \$x;          # Backs up the SV associated with `$x`.
       defer { \$x = \$backup; }   # Restores the SV associated with `$x`.
    
       for my $ele ( 1 .. 3 ) {
          \$x = \$ele;             # `$x` is associated with SV from list.
    
          say $x;                  # Accesses the only `$x`.
          f();
       }
    }
    
    say $x;                        # Accesses the only `$x`.
    

    输出:

    1
    1
    2
    2
    3
    3
    9
    
    • 3

相关问题

  • 传输矩阵时,写一行和两行有什么区别?

  • Rust 特征对象的输入和输出类型不匹配

  • Delphi 中带有两个计数器的 for 循环

  • 如何跟踪您在 Ansible 循环中的位置?

  • 如何在 kdb/Q 表中使用带有 if 语句的 for 循环?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve