开发者

Declaring a scalar inside an if statement?

开发者 https://www.devze.com 2023-03-03 23:37 出处:网络
Why can\'t I declare a scalar variable inside an if statement? Does it have something to do with the scope of the开发者_运维百科 variable?Every block {...} in Perl creates a new scope.This includes ba

Why can't I declare a scalar variable inside an if statement? Does it have something to do with the scope of the开发者_运维百科 variable?


Every block {...} in Perl creates a new scope. This includes bare blocks, subroutine blocks, BEGIN blocks, control structure blocks, looping structure blocks, inline blocks (map/grep), eval blocks, and the bodies of statement modifier loops.

If a block has an initialization section, that section is considered within the scope of the following block.

if (my $x = some_sub()) {
    # $x in scope here
} 
# $x out of scope

In a statement modifier loop, the initialization section is not contained within the scope of the pseudo block:

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

# $x, $y, and $z are still in scope and each is set to 1


Who says you can't?

#! /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

Works perfectly! Of course it makes no sense since what are you comparing $foo too? It has no value.

Can you give me an example of what you're doing and the results you're getting?

Or, is this more what you mean?:

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

So, which one do you mean?


Just to follow up my comment. Statements such as the following is perfectly legal:

if( my( $foo, $bar ) = $baz =~ /^(.*?)=(.*?)$/ ) {
  # Do stuff
}

Courtesy of one of my colleagues.


There's an exception: You may not conditionally declare a variable and use it under different conditions. This means the following isn't allowed:

my $x = ... if ...;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号