scope of $name in: (my $name = 123) && something-involving-$name;

Y

Yakov

I find it strange in the examlpe below

1 open(my $fh, my $name="</no/such/file") ||
2 warn "Error name=$name\n";
3 print "name=$name";

that $name is not in the scope, at line 2 (in the warn() arg).

The assignment to $name in line 1 definitely already happened. So
how come $name is not known at line 2 ? Is this a feature or a bug ?
What is the explanation ? Does perl, like, wait for the semicolon to
add $name to the hashtable or variables ?

This is counterintuitive to me ... (comparing to C foo() { int x=1,
y=x; } )

Thanks
Yakov
 
J

John W. Krahn

Yakov said:
I find it strange in the examlpe below

1 open(my $fh, my $name="</no/such/file") ||
2 warn "Error name=$name\n";
3 print "name=$name";

that $name is not in the scope, at line 2 (in the warn() arg).

The assignment to $name in line 1 definitely already happened. So
how come $name is not known at line 2 ? Is this a feature or a bug ?
What is the explanation ? Does perl, like, wait for the semicolon to
add $name to the hashtable or variables ?

perldoc perlsub
[snip]
The declared variable is not introduced (is not visible) until after
the current statement. Thus,

my $x = $x;

can be used to initialize a new $x with the value of the old $x, and
the expression

my $x = 123 and $x == 123

is false unless the old $x happened to have the value 123.


So when perl compiles the line:

open(my $fh, my $name="</no/such/file") || warn "Error name=$name\n";

the second $name refers to a different variable then the first $name.

$ perl -Mwarnings -Mstrict -ce'open(my $fh, my $name="</no/such/file") || warn
"Error name=$name\n"'
Global symbol "$name" requires explicit package name at -e line 1.
-e had compilation errors.



John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top