Typeglobs, the Symbol Table and Metaprogramming

Source filters (Filter::Simple) and keyword plugins (Keyword::Simple, XS::Parse::Keyword) can extend syntax. Use them very sparingly.

use v5.36;
no strict 'refs';                     # needed for symbolic references

# Symbol tables are hashes: %main::, %My::Package::
for my $name (sort keys %main::) { }          # all symbols in main
say "sub exists" if defined &{"My::Module::helper"};

# Generate accessors at runtime
package Person;
for my $field (qw(name age email)) {
    no strict 'refs';
    *{"Person::$field"} = sub ($self, @v) {   # glob assignment installs a sub
        $self->{$field} = $v[0] if @v;
        return $self->{$field};
    };
}

# Aliasing
*short = \&very_long_function_name;   # alias a sub
*PI = \3.14159;                        # read-only constant scalar via glob

# Calling subs by name
my $sub_name = 'process_' . $type;
my $code = __PACKAGE__->can($sub_name) or die "No handler for $type";
$code->($data);

# String eval (compile code at runtime: powerful but dangerous with untrusted input)
my $sum = eval "2 + 3 * 4";
die $@ if $@;

# Local monkey patching
{
    no warnings 'redefine';
    local *LWP::UserAgent::get = sub { fake_response() };   # override temporarily (testing)
    run_code_under_test();
}

# Introspection
use B qw(svref_2object);
my $cv = svref_2object(\&Person::name);
say $
…