[Chicago-talk] no strict refs question
Steven Lembark
lembark at wrkhors.com
Mon Mar 8 00:07:34 CST 2004
-- Jay Strauss <me at heyjay.com>
> Can I do:
>
>> cat j
># !/usr/bin/perl
> $app = "filename";
> my @a = qw/app/;
>
> foreach my $var (@a) {
> print "$$var\n";
> }
>
>> ./j
> filename
>
>
> With a "my" variable for $app? as in:
>
>> cat j
># !/usr/bin/perl
> my $app = "filename"; ### notice the my ###
> my @a = qw/app/;
>
> foreach my $var (@a) {
> print "$$var\n";
> }
You cannot access lexical variables via the symbol
table. Code outside the lexical scope of the code
has no access to them (short of some heavy-duty
magic such as /dev/kmem). Code w/in the lexical
scope can pass out ref's or values.
The tricks with strict all use the symbol table
to access global variables.
For example:
{
package Whatever;
my $foo = 'bletch';
our $bar = 'blort';
}
Since $bar is in the symbol table via "our" (or "use vars"
or $Whatever::bar) you can play games with $caller . '::' .
'bar' and see it. On the other hand, $foo is in accessable
to anything outside of its lexical scope [methinks even
within the same package if the package is broken up across
modules?].
This means that with strict turned off and
$var = join '::', $caller, 'bar';
then $$var will get you 'blort'. You canot pull the same
trick with $foo.
lexical var's behave pretty much the way stack var's do
in C: they are placeholders for the compiler to use
dynamically allocated storage rather than locations that
get fed into %:: for access by name. They behave pretty
much like C's stack variables, if that helps.
Aside: the lack of package affilliation in lexicals can
be handy for sharing values across packages/classes:
...
my $verbose = $cmdline->{verbose} || 0;
package This;
print ... if $verbose;
package That;
print ... if $verbose;
Both packages share the same '$verbose' variable if they
are in the same file. This can be handy for sharing data
across multiple classes w/in a module (e.g., verbose set
or debug set from the command line).
--
Steven Lembark 2930 W. Palmer
Workhorse Computing Chicago, IL 60647
+1 888 359 3508
More information about the Chicago-talk
mailing list