在if语句中声明一个标量?

ian*_*215 2 perl

为什么我不能在if语句中声明标量变量?它与变量的范围有关吗?

Eri*_*rom 8

{...}Perl中的每个块都会创建一个新的范围.这包括裸块,子程序块,BEGIN块,控制结构块,循环结构块,内联块(map/grep),eval块和语句修饰符循环体.

如果块具有初始化部分,则认为该部分在以下块的范围内.

if (my $x = some_sub()) {
    # $x in scope here
} 
# $x out of scope
Run Code Online (Sandbox Code Playgroud)

在语句修饰符循环中,初始化部分不包含在伪块的范围内:

$_ = 1 for my ($x, $y, $z);

# $x, $y, and $z are still in scope and each is set to 1
Run Code Online (Sandbox Code Playgroud)


Dav*_* W. 5

谁说你做不到?

#! /usr/bin/env perl

use warnings;
no warnings qw(uninitialized);
use strict;
use feature qw(say);
use Data::Dumper;

my $bar;

if (my $foo eq $bar) {
    say "\$foo and \$bar match";
}
else {
    say "Something freaky happened";
}

$ ./test.pl 
$foo and $bar match
Run Code Online (Sandbox Code Playgroud)

完美的工作!当然,没有任何意义,因为你也在比较$foo什么?它没有任何价值.

你能举例说明你正在做什么以及你得到的结果吗?

或者,这更像是什么意思?:

if (1 == 1) {
   my $foo = "bar";
   say "$foo";    #Okay, $foo is in scope
}

say "$foo;"    #Fail: $foo doesn't exist because it's out of scope
Run Code Online (Sandbox Code Playgroud)

那么,你的意思是哪一个?