Efficiency patchlet for pp_aassign()
[p5sagit/p5-mst-13.2.git] / lib / Symbol.pm
1 package Symbol;
2
3 =head1 NAME
4
5 Symbol - 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
28 C<Symbol::gensym> creates an anonymous glob and returns a reference
29 to it.  Such a glob reference can be used as a file or directory
30 handle.
31
32 For backward compatibility with older implementations that didn't
33 support anonymous globs, C<Symbol::ungensym> is also provided.
34 But it doesn't do anything.
35
36 C<Symbol::qualify> turns unqualified symbol names into qualified
37 variable names (e.g. "myvar" -E<gt> "MyPackage::myvar").  If it is given a
38 second parameter, C<qualify> uses it as the default package;
39 otherwise, it uses the package of its caller.  Regardless, global
40 variable names (e.g. "STDOUT", "ENV", "SIG") are always qualfied with
41 "main::".
42
43 Qualification applies only to symbol names (strings).  References are
44 left unchanged under the assumption that they are glob references,
45 which are qualified by their nature.
46
47 =cut
48
49 BEGIN { require 5.002; }
50
51 require Exporter;
52 @ISA = qw(Exporter);
53
54 @EXPORT = qw(gensym ungensym qualify);
55
56 my $genpkg = "Symbol::";
57 my $genseq = 0;
58
59 my %global = map {$_ => 1} qw(ARGV ARGVOUT ENV INC SIG STDERR STDIN STDOUT);
60
61 sub gensym () {
62     my $name = "GEN" . $genseq++;
63     local *{$genpkg . $name};
64     \delete ${$genpkg}{$name};
65 }
66
67 sub ungensym ($) {}
68
69 sub qualify ($;$) {
70     my ($name) = @_;
71     if (!ref($name) && index($name, '::') == -1 && index($name, "'") == -1) {
72         my $pkg;
73         # Global names: special character, "^x", or other. 
74         if ($name =~ /^([^a-z])|(\^[a-z])$/i || $global{$name}) {
75             $pkg = "main";
76         }
77         else {
78             $pkg = (@_ > 1) ? $_[1] : caller;
79         }
80         $name = $pkg . "::" . $name;
81     }
82     $name;
83 }
84
85 1;