Commit | Line | Data |
c53d2df2 |
1 | #!/usr/bin/env perl |
f10f6217 |
2 | use strict; |
3 | use warnings; |
c53d2df2 |
4 | use lib 't/lib'; |
f10f6217 |
5 | use Test::More; |
13f4d7c3 |
6 | use Test::Fatal; |
f10f6217 |
7 | |
8 | { |
e94260da |
9 | package My::Package::Stash; |
f10f6217 |
10 | use strict; |
11 | use warnings; |
12 | |
e94260da |
13 | use base 'Package::Stash'; |
f10f6217 |
14 | |
15 | use Symbol 'gensym'; |
16 | |
e55970bc |
17 | sub new { |
18 | my $class = shift; |
19 | my $self = $class->SUPER::new(@_); |
20 | $self->{namespace} = {}; |
21 | return $self; |
f10f6217 |
22 | } |
23 | |
15c104e2 |
24 | sub add_symbol { |
f10f6217 |
25 | my ($self, $variable, $initial_value) = @_; |
26 | |
e3ad44fd |
27 | (my $name = $variable) =~ s/^[\$\@\%\&]//; |
f10f6217 |
28 | |
29 | my $glob = gensym(); |
30 | *{$glob} = $initial_value if defined $initial_value; |
31 | $self->namespace->{$name} = *{$glob}; |
32 | } |
33 | } |
34 | |
35 | # No actually package Foo exists :) |
e94260da |
36 | my $foo_stash = My::Package::Stash->new('Foo'); |
f10f6217 |
37 | |
e94260da |
38 | isa_ok($foo_stash, 'My::Package::Stash'); |
39 | isa_ok($foo_stash, 'Package::Stash'); |
f10f6217 |
40 | |
41 | ok(!defined($Foo::{foo}), '... the %foo slot has not been created yet'); |
15c104e2 |
42 | ok(!$foo_stash->has_symbol('%foo'), '... the foo_stash agrees'); |
f10f6217 |
43 | |
20336547 |
44 | is(exception { |
15c104e2 |
45 | $foo_stash->add_symbol('%foo' => { one => 1 }); |
20336547 |
46 | }, undef, '... the %foo symbol is created succcessfully'); |
f10f6217 |
47 | |
48 | ok(!defined($Foo::{foo}), '... the %foo slot has not been created in the actual Foo package'); |
15c104e2 |
49 | ok($foo_stash->has_symbol('%foo'), '... the foo_stash agrees'); |
f10f6217 |
50 | |
15c104e2 |
51 | my $foo = $foo_stash->get_symbol('%foo'); |
f10f6217 |
52 | is_deeply({ one => 1 }, $foo, '... got the right package variable back'); |
53 | |
54 | $foo->{two} = 2; |
55 | |
15c104e2 |
56 | is($foo, $foo_stash->get_symbol('%foo'), '... our %foo is the same as the foo_stashs'); |
f10f6217 |
57 | |
58 | ok(!defined($Foo::{bar}), '... the @bar slot has not been created yet'); |
59 | |
20336547 |
60 | is(exception { |
15c104e2 |
61 | $foo_stash->add_symbol('@bar' => [ 1, 2, 3 ]); |
20336547 |
62 | }, undef, '... created @Foo::bar successfully'); |
f10f6217 |
63 | |
64 | ok(!defined($Foo::{bar}), '... the @bar slot has still not been created'); |
65 | |
66 | ok(!defined($Foo::{baz}), '... the %baz slot has not been created yet'); |
67 | |
20336547 |
68 | is(exception { |
15c104e2 |
69 | $foo_stash->add_symbol('%baz'); |
20336547 |
70 | }, undef, '... created %Foo::baz successfully'); |
f10f6217 |
71 | |
72 | ok(!defined($Foo::{baz}), '... the %baz slot has still not been created'); |
73 | |
74 | done_testing; |