Perl Expert · Lesson 1 · On the house

Typeglobs and symbol tables

*name; *FOO{SCALAR}; stash slots. Lesson 1 is free — on the house.

Lessons · Perl Expert · Lesson 1 of 10 · On the house

Typeglobs and symbol tables

*name; *FOO{SCALAR}; stash slots.

Illustration for Perl
Lesson 1 is on the house.

A typeglob is the symbol-table entry for a bare name. *foo holds every slot that name can mean: SCALAR, ARRAY, HASH, CODE, IO, FORMAT, and GLOB. Assigning *alias = *real; aliases all slots; assigning *alias = \ℜ aliases only the CODE slot.

Read one slot with *FOO{SCALAR}, *FOO{ARRAY}, *FOO{HASH}, *FOO{CODE}, *FOO{IO}. Each returns a reference to that slot's value (or undef if empty). Package stashes are hashes named like %main:: or %Foo:: — keys are names, values are typeglobs.

*STDOUT = *STDERR; redirects prints on STDOUT to STDERR's IO slot for the dynamic scope if you localize: local *STDOUT = *STDERR;. Localization of typeglobs is how temporary redirections and monkey-patches stay contained.

Under strict, barewords for filehandles still resolve through typeglobs. Prefer lexical filehandles (open my $fh, ...) in new code; typeglobs remain the machinery behind package filehandles and symbol aliasing.

Misses: treating *foo as a scalar variable, assigning a plain string to a typeglob expecting a slot fill (use a reference: *foo = \$scalar), or mutating %Foo:: without understanding you are editing the live stash.

typeglobs

#!/usr/bin/env perl
use strict;
use warnings;

package Demo;
our $count = 7;
our @items = qw(a b);
sub greet { return "hi" }

package main;
my $sref = *Demo::count{SCALAR};
my $aref = *Demo::items{ARRAY};
my $cref = *Demo::greet{CODE};
print "count=$$sref\n";
print "items=@$aref\n";
print "greet=", $cref->(), "\n";

*alias = *Demo::count;
print "alias=$alias\n";
Match this when you type.

Quiz

What does *Demo::count{SCALAR} return?

Quiz

What does *alias = *Demo::count do?

Quiz

What lives in %Demo:: ?

Quiz

How do you alias only a sub?

Check

Match the still for: Typeglobs and symbol tables.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.