How to insert directly into the wallet?

I am trying to write a pragma to define a bunch of constants, for example:

use many::constant
    one_constant => 1,
    other_constant => 2,
;

The relevant part of my import looks like

package many::constant;

use strict;
use warnings;

sub import {
    my ($class, @constants) = @_;

    my $caller_nms = do {
        no strict 'refs';
        \%{caller.'::'}
    };

    while (my ($name, $value) = splice @constants, 0, 2) {
        *{$caller_nms->{$name}} = sub () { $value };
    }
}

I expect stash $caller_nmsto automatically revive when assigned in this way, but I get the error message “Unable to use undefined value as a symbol reference”. Is there a way to get this task to work as I expect? I ended up changing the assignment:

my $caller_glob = do {
    no strict 'refs';
    \*{caller.'::'.$name}
};
*$caller_glob = sub () { $value };

but for me it is less elegant.

+4
source share
1 answer

Simply use use constantas a baseline and really explore the source: constant.pm.

This is essentially what he does:

my $pkg = caller;
# ...
{
    no strict 'refs';
    my $full_name = "${pkg}::$name";
    # ...
    my @list = @_;
    *$full_name = sub () { @list };
}

, constant : constant #Defining multiple constants at once

use strict;
use warnings;

use constant {
    one_constant => 1,
    other_constant => 2,
};

print one_constant, ' - ', other_constant, "\n";

:

1 - 2
+4

Source: https://habr.com/ru/post/1539337/


All Articles