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"; 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.)#!/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";
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:
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.#!/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";
In reply to Re: Benchmark.pm's scoping behavior
by chromatic
in thread Benchmark.pm's scoping behavior
by Russ
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |