http://www.perlmonks.org?node_id=114561

asinghvi has asked for the wisdom of the Perl Monks concerning the following question:

My program looks like this.

....
$var1 ... $var2... $var3 ... sub get_vars { local (*variables) = *main::; #-- Some checking on certain variables }

When I call get_vars before defining $var1, $var2, $var3, then %variables does not contain them.
When I call get_vars after defining $var1, $var2, $var3 then %variables has them. Isn't *variables reading *main:: at compile time. What am I missing?

Thanks

Replies are listed 'Best First'.
Re: using symbol table lookup
by dragonchild (Archbishop) on Sep 25, 2001 at 20:04 UTC
    What on earth do you want to fiddle with the symbol table for?? It's dangerous, messy, and there's better ways to do it.

    As for your questions, *variables is bound to *main:: when you bind it. Hence, if the variable hasn't been created yet, it's not in *main::. Compilation doesn't populate anything. All it does is convert the script to opcodes. When those opcodes execute, that's when the SV's are created, and a reference entered into *main::.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      My purpose is that my perl scripts read many text files
      So rather than checking each one in each script, I thought
      I would always make my filename variables always as
      "something_file". And have a standard subroutine that checks
      all %main:: scalar variables  =~ /\_file/ and do the checks
      on each entry (Like file exists, file is readable etc.)
      .
        Use Exporter, or write a subroutine in each program that returns the filename, or a hash reference of values.

        Leave symbol-table mucking about for when there's really no other way to do that (basically run-time code generation).

        Rather odd way to do it I would have thought. Is there something inherently wrong with this approach:

        my $dir = 'c:/'; opendir DIR, $dir or die "Oops cna't open $dir $!\n"; my @files = grep { /\.pl$/ } readdir DIR; close DIR; $_ = $dir.$_ for @files; # add full path print "Here are all the files:\n"; print "$_\n" for @files;

        This finds all the files in my root dir which end in .pl but I could use the regex in the grep to match anything. I don't see any reason to mess with the symbol table. Just wrap this sort of code in a sub that you can call from wherever....

        cheers

        tachyon

        s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print