in reply to Benchmark.pm's scoping behavior

Here's another example just to show the difference between scopes:
#!/usr/bin/perl -w use strict; package R; my $R = 10; use vars qw( $var ); $var = 20; package main; print "R is >>$R<<\n"; package R; print "R is >>$R<<\n"; print "var is >>$var<<\n";
Nifty, everything prints. All in the same file, everything okay, right? Let's mess with scoping a little bit:
#!/usr/bin/perl -w use strict; { package R; my $R = 10; use vars qw( $var ); $var = 20; } package main; print "R is >>$R<<\n"; print "var is >>$R::var<<\n"; package R; print "R is >>$R<<\n"; print "var is >>$var<<\n";
Whoops, errors. $R is unavailable in both main:: and R::, while $var is unavailable in main::. Here's how to fix that:
#!/usr/bin/perl -w use strict; { package R; my $R = 10; use vars qw( $var ); $var = 20; } package main; # print "R is >>$R<<\n"; print "var is >>$R::var<<\n"; package R; # print "R is >>$R<<\n"; print "var is >>$var<<\n";
There's no way to get to $R, so we'll comment it out. Lexical (or my) variables have block scope, if they're in a block, or file-scope, if they're not. That's why the first example worked, in the main package. (Yes, I put those braces in there just for this point.)

Variables declared with 'use vars' have package scope, so we can switch to package R again and print $var without prepending the package name, as we have to do when we're in package main. Presumably the new our works much the same way in 5.6.

I can't let the idea of lexical variables and scope go away without making at least one comment about the misunderstood and feared closure. Take a look at this:

#!/usr/bin/perl -w use strict; { package R; my $R = 10; use vars qw( $var ); $var = 20; sub show_R { $R }; } package main; print "var is >>$R::var<<\n"; print "var is ", R::show_R(), "\n"; package R; print "var is >>$var<<\n"; print "var is ", show_R(), "\n";
Nifty, hmm? Because $R is available in the same scope where show_R() is defined, the subroutine has access to it, even when called outside of that scope. That's all a closure is, but that's not all it's good for.

Replies are listed 'Best First'.
RE:(2) Benchmark.pm's scoping behavior
by Russ (Deacon) on Jun 21, 2000 at 10:57 UTC
    See above in my reply to btrott. You have provided a great discussion, and have certainly taught me something.

    Closures are cool. I've never had any trouble understanding lexical variables within some other block (like a sub). I guess I have never tried to declare a closure at file scope, so I've haven't learned to fear them. It wouldn't have worked for me (at file scope), before today, so I guess the timing is better this way. :-)

    Thanks for sharing your knowledge...

    Russ