免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 2821 | 回复: 10
打印 上一主题 下一主题

为什么“for”语句无法改变全局变量的内容?【已解决】 [复制链接]

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-06-09 13:33 |只看该作者 |倒序浏览
本帖最后由 ttcn_cu 于 2010-06-09 14:51 编辑
  1. #!/usr/bin/perl -w
  2. use strict;
  3. my $var="default";
  4. my @t = qw (aa bb cc);
  5. for $var (@t){
  6.     print "$var\n";
  7.     printit();
  8. }

  9. sub printit{
  10.     print "$var\n";
  11. }
复制代码
执行结果:
  1. aa
  2. default
  3. bb
  4. default
  5. cc
  6. default
复制代码
期待结果
  1. aa
  2. aa
  3. bb
  4. bb
  5. cc
  6. cc
复制代码

论坛徽章:
78
双子座
日期:2013-10-15 08:50:09天秤座
日期:2013-10-16 18:02:08白羊座
日期:2013-10-18 13:35:33天蝎座
日期:2013-10-18 13:37:06狮子座
日期:2013-10-18 13:40:31双子座
日期:2013-10-22 13:58:42戌狗
日期:2013-10-22 18:50:04CU十二周年纪念徽章
日期:2013-10-24 15:41:34巨蟹座
日期:2013-10-24 17:14:56处女座
日期:2013-10-24 17:15:30双子座
日期:2013-10-25 13:49:39午马
日期:2013-10-28 15:02:15
2 [报告]
发表于 2010-06-09 14:08 |只看该作者
  1. for (@t){
  2.     $var = $_;
  3.     print "$var\n";

  4.     printit();

  5. }
复制代码
这样可以

论坛徽章:
0
3 [报告]
发表于 2010-06-09 14:33 |只看该作者
回复 1# ttcn_cu


Foreach Loops
  The "foreach" loop iterates over a normal list value and sets the
  variable VAR to be each element of the list in turn. If the variable is
  preceded with the keyword "my", then it is lexically scoped, and is
  therefore visible only within the loop. Otherwise, the variable is
  implicitly local to the loop and regains its former value upon exiting
  the loop. If the variable was previously declared with "my", it uses
  that variable instead of the global one, but it's still localized to the
  loop
. This implicit localisation occurs *only* in a "foreach" loop.

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
4 [报告]
发表于 2010-06-09 14:51 |只看该作者
我确实用了2楼的处理方法。
非常感谢3楼详细的解答

论坛徽章:
0
5 [报告]
发表于 2010-06-09 16:30 |只看该作者
回复 4# ttcn_cu


    没有必要转存一次啊,声明改为 our $var = '...' 也可以

论坛徽章:
0
6 [报告]
发表于 2010-06-09 16:56 |只看该作者
推荐用主流的写法。
非主流的话会遭人围观的。

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
7 [报告]
发表于 2010-06-09 17:02 |只看该作者
回复 6# nuclearxin


    推荐写法是哪种?

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
8 [报告]
发表于 2010-06-09 17:04 |只看该作者
回复 5# dugu072_cu


    用our的话,会“污染”其他模块吧?

论坛徽章:
0
9 [报告]
发表于 2010-06-09 17:15 |只看该作者
回复 7# ttcn_cu

init:
思路清晰
不用用以引起歧义的
语句
如果觉得必须用这样的语句
无限 loop 到 init那里。。。。

论坛徽章:
0
10 [报告]
发表于 2010-06-09 18:23 |只看该作者
回复 8# ttcn_cu


    our 只是放到了 符号表 而已,最大的影响也只是占了一点点内存,至于说污染其他模块,除非其他模块 特地的用包全名 来污染,不然怎么可能被影响,our 的引入,目的就是限定作用域的嘛~
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP