YaoRaoLov 2014-01-02 18:43 采纳率: 50%
浏览 530
已采纳

在 Perl 中我应该如何使用"my"关键字?

I keep seeing the "my" keyword in front of variable names in example Perl scripts online but I have no idea what it means. I tried reading the manual pages and other sites online but I'm having difficulty discerning what it is for given the difference between how I see it used and the manual.

For example, its used to get the length of the array in this post: Find size of an array in Perl

But the manual says:

A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses.

What does it do and how is it used?

转载于:https://stackoverflow.com/questions/20889609/how-should-i-use-the-my-keyword-in-perl

  • 写回答

3条回答 默认 最新

  • 妄徒之命 2014-01-02 20:00
    关注

    my restricts the scope of a variable. The scope of a variable is where it can be seen. Reducing a variable's scope to where the variable is needed is a fundamental aspect of good programming. It makes the code more readable and less error-prone, and results in a slew of derived benefits.

    If you don't declare a variable using my, a global variable will be created instead. This is to be avoided. Using use strict; tells Perl you want to be prevented from implicitly creating global variables, which is why you should always use use strict; (and use warnings;) in your programs.


    Related reading: Why use use strict; and use warnings;?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?