Don't require() in a signal handler
[p5sagit/p5-mst-13.2.git] / lib / Symbol.pm
CommitLineData
c07a80fd 1package Symbol;
2
3=head1 NAME
4
5Symbol - manipulate Perl symbols and their names
6
7=head1 SYNOPSIS
8
9 use Symbol;
10
11 $sym = gensym;
12 open($sym, "filename");
13 $_ = <$sym>;
14 # etc.
15
16 ungensym $sym; # no effect
17
18 print qualify("x"), "\n"; # "Test::x"
19 print qualify("x", "FOO"), "\n" # "FOO::x"
20 print qualify("BAR::x"), "\n"; # "BAR::x"
21 print qualify("BAR::x", "FOO"), "\n"; # "BAR::x"
22 print qualify("STDOUT", "FOO"), "\n"; # "main::STDOUT" (global)
23 print qualify(\*x), "\n"; # returns \*x
24 print qualify(\*x, "FOO"), "\n"; # returns \*x
25
26=head1 DESCRIPTION
27
28C<Symbol::gensym> creates an anonymous glob and returns a reference
29to it. Such a glob reference can be used as a file or directory
30handle.
31
32For backward compatibility with older implementations that didn't
33support anonymous globs, C<Symbol::ungensym> is also provided.
34But it doesn't do anything.
35
36C<Symbol::qualify> turns unqualified symbol names into qualified
7c584b33 37variable names (e.g. "myvar" -E<gt> "MyPackage::myvar"). If it is given a
c07a80fd 38second parameter, C<qualify> uses it as the default package;
39otherwise, it uses the package of its caller. Regardless, global
40variable names (e.g. "STDOUT", "ENV", "SIG") are always qualfied with
41"main::".
42
43Qualification applies only to symbol names (strings). References are
44left unchanged under the assumption that they are glob references,
45which are qualified by their nature.
46
47=cut
48
3dc8e7ab 49BEGIN { require 5.002; }
c07a80fd 50
51require Exporter;
52@ISA = qw(Exporter);
53
54@EXPORT = qw(gensym ungensym qualify);
55
56my $genpkg = "Symbol::";
57my $genseq = 0;
58
7c584b33 59my %global = map {$_ => 1} qw(ARGV ARGVOUT ENV INC SIG STDERR STDIN STDOUT);
c07a80fd 60
6adf1df6 61#
62# Note that we never _copy_ the glob; we just make a ref to it.
63# If we did copy it, then SVf_FAKE would be set on the copy, and
64# glob-specific behaviors (e.g. C<*$ref = \&func>) wouldn't work.
65#
c07a80fd 66sub gensym () {
67 my $name = "GEN" . $genseq++;
6adf1df6 68 my $ref = \*{$genpkg . $name};
69 delete $$genpkg{$name};
70 $ref;
c07a80fd 71}
72
73sub ungensym ($) {}
74
75sub qualify ($;$) {
76 my ($name) = @_;
49da0595 77 if (!ref($name) && index($name, '::') == -1 && index($name, "'") == -1) {
c07a80fd 78 my $pkg;
79 # Global names: special character, "^x", or other.
80 if ($name =~ /^([^a-z])|(\^[a-z])$/i || $global{$name}) {
81 $pkg = "main";
82 }
83 else {
84 $pkg = (@_ > 1) ? $_[1] : caller;
85 }
86 $name = $pkg . "::" . $name;
87 }
88 $name;
89}
90
911;