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

查看:28
本文介绍了我应该如何使用“我的"?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天全站免登陆