我应该如何使用“我的" Perl中使用关键字? [英] How should I use the "my" keyword in Perl?

查看:97
本文介绍了我应该如何使用“我的" Perl中使用关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在示例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.

例如,它用于获取本文中数组的长度: 在Perl中查找数组的大小

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

但是手册说:

A my声明列出的变量在本地(按词法)对于 包含块,文件或评估.如果列出了多个值,则 列表必须放在括号中.

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?

推荐答案

my限制作用域.可以看到变量的范围.将变量的范围缩小到需要该变量的位置是良好编程的基本方面.它使代码更具可读性,并且不易出错,并带来了很多好处.

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.

如果不使用my声明变量,则会创建一个全局变量.这是要避免的.使用use strict;告诉Perl您希望避免隐式创建全局变量,这就是为什么您应该在程序中始终使用use strict;(和use warnings;)的原因.

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.

相关阅读:为什么使用use strict;use warnings;?

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

这篇关于我应该如何使用“我的" Perl中使用关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆