本文介绍了为什么用“my"声明 Perl 变量?在文件范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Perl 并试图理解变量作用域.我知道 my $name = 'Bob'; 将声明一个局部变量 inside 一个子,但是你为什么要使用 my 关键字在全球范围?是否只是一个好习惯,以便您可以安全地将代码移动到子中?

I'm learning Perl and trying to understand variable scope. I understand that my $name = 'Bob'; will declare a local variable inside a sub, but why would you use the my keyword at the global scope? Is it just a good habit so you can safely move the code into a sub?

我看到很多执行此操作的示例脚本,我想知道为什么.即使使用 use strict,当我删除 my 时它也不会抱怨.我尝试比较使用和不使用它的行为,但我看不出任何区别.

I see lots of example scripts that do this, and I wonder why. Even with use strict, it doesn't complain when I remove the my. I've tried comparing behaviour with and without it, and I can't see any difference.

这是执行此操作的一个示例:

#!/usr/bin/perl
use strict;
use warnings;

use DBI;

my $dbfile = "sample.db";

my $dsn      = "dbi:SQLite:dbname=$dbfile";
my $user     = "";
my $password = "";
my $dbh = DBI->connect($dsn, $user, $password, {
   PrintError       => 0,
   RaiseError       => 1,
   AutoCommit       => 1,
   FetchHashKeyName => 'NAME_lc',
});

# ...

$dbh->disconnect;

更新

当我测试这种行为时,我似乎很不走运.这是我测试的脚本:

Update

It seems I was unlucky when I tested this behaviour. Here's the script I tested with:

use strict;

my $a = 5;
$b = 6;

sub print_stuff() {
    print $a, $b, "\n"; # prints 56
    $a = 55;
    $b = 66;
}

print_stuff();
print $a, $b, "\n"; # prints 5566

正如我从这里的一些答案中了解到的,$a$b 是已经声明的特殊变量,因此编译器不会抱怨.如果我在该脚本中将 $b 更改为 $c,则会报错.

As I learned from some of the answers here, $a and $b are special variables that are already declared, so the compiler doesn't complain. If I change the $b to $c in that script, then it complains.

至于为什么在全局范围内使用 my $foo,看起来 file 范围实际上可能不是 global 范围.

As for why to use my $foo at the global scope, it seems like the file scope may not actually be the global scope.

推荐答案

这只是很好的做法.作为个人规则,我尽量将变量保持在尽可能小的范围内.如果一行代码看不到一个变量,那么它就不能以意想不到的方式来干扰它.

It's just good practice. As a personal rule, I try to keep variables in the smallest scope possible. If a line of code can't see a variable, then it can't mess with it in unexpected ways.

我很惊讶你发现脚本在 use strict 下运行,但没有 my.这通常是不允许的:

I'm surprised that you found that the script worked under use strict without the my, though. That's generally not allowed:

$ perl -E 'use strict; $db = "foo"; say $db'
Global symbol "$db" requires explicit package name at -e line 1.
Global symbol "$db" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
$ perl -E 'use strict; my $db = "foo"; say $db'
foo

变量 $a$b 是豁免的:

Variables $a and $b are exempt:

$ perl -E 'use strict; $b = "foo"; say $b'
foo

但我不知道您将如何使您发布的代码在严格且缺少 my 的情况下工作.

But I don't know how you would make the code you posted work with strict and a missing my.

这篇关于为什么用“my"声明 Perl 变量?在文件范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:57