- Perl ›
- Module creation ›
- here
Take a peek inside the symbol table
Perl has a symbol table that programmers can reference and make changes to. Perl is more flexible and adaptable than other languages, but one of the features that makes it so powerful is the symbol table.
The symbol table is just a hash named%main::. From the hash%main::, you can see all the subroutine and a package variable of the script being executed. (Excluding a lexical variable)
Take a peek at the contents of the symbol table
# main A symbol table containing the contents of the package # %main::Another name for %main::%::</pre> <h3>Know the contents of a package variable through the symbol table</h3> <pre> our $num = 1; ${$main::{num}};
A detailed explanation is given in the explanation of typeglobs. Here, remember Perl's ability to know the contents of a package variable and subroutine from the symbol table.
This is an example that outputs the contents of the symbol table.
use strict; use warnings; # Take a peek at the symbol table. # This subroutine is registered in the symbol table at compile time. # Package declaration is not made, so it implicitly belongs to the main package # Will be. our $num = 1; sub func { return 2; } print "1: Take a peek at the symbol table\n"; require Data::Dumper; # The print symbol table is just a hash. # What belongs to the main package # You can refer to it with the name %main::. Data::Dumper->Dump([\%main::], [qw(* main::)]), "\n"; print "2: View the contents of num and func in the main package.\n"; print $main::{num}, "\n"; # You can also use::as an alias for main::. print $::{num}, "\n"; print $main::{func}, "\n"; print $::{func}, "\n\n"; print "3: Get the contents of the variable from the symbol table.\n"; # Extract the scalar variable from'* main::num' with ${}. my $num_from_symbol = ${$main::{num}}; print $num_from_symbol;
Meaning of output result
print $main::{num}; # Output result * main::num
The above output will be displayed as * main::num. The * symbol is a symbol that represents a typeglob. The type glob will be explained next time.