Is it possible to dynamically localize multiple global variables without using eval?

Asked 1 years ago, Updated 1 years ago, 116 views

If global variables $foo, $bar, $buz exist and try to localize them only within a specific scope, I think:

use strict;
use warnings;
use v5.10;

our($foo,$bar,$buz) = qw(foo barbuz);

UPPER_CASE_WORLD: {
    # Capitalize global variables for this scope only
    no strict 'refs';
    local($foo,$bar,$buz) = map {uc${":$_"}}qw(foo barbuz);

    say$foo,$bar,$buz;
}

say$foo,$bar,$buz;

1;

When you extend this to "many unspecified global variables", if you use the for loop as it is, you will not be able to produce localized variables outside of for.

#Uppercase many and unspecified global variables
    no strict 'refs';
    my@globals=qw(foo bar buzz);
    local${"::$_"}=uc${"::$_"} for @globals;

    # Oh, no, no, no, no, no, no, no, no, no.
    say$foo,$bar,$buz;

If you have no choice but to rely on eval, you may need to eat the block itself.I feel a little forced.

use strict;
use warnings;
use v5.10;

our($foo,$bar,$buz) = qw(foo barbuz);

no strict 'refs';
my@globals=qw(foo bar buzz);
my$bunch_of_locals=joinq{},map{
    "local\${':$_'}=uc\${':$_'};"
} @globals;

event<<"__UPPER_CASE_WORLD";
{
    # Capitalize many and unspecified global variables
    $bunch_of_locals

    # Do I have to stop here?
    say \$foo, \$bar, \$buz;
}
__UPPER_CASE_WORLD

say$foo,$bar,$buz;

1;

If you want to localize many and unspecified global variables at a certain scope, can you write them easily without using eval?

perl

2022-09-30 20:21

1 Answers

For example, how about the following?
The concept saves the value at the beginning of the scope and returns it to the end (i.e., manual local)

use strict;
use warnings;
use v5.10;

our($foo,$bar,$buz) = qw(foo barbuz);

# sugar-coated syntax function
subusing(&@){
    my$code=shift;
    my@v=@_;# Save variable contents
    $code->(@_);
    my$i = 0;
    $_=$v[$i++] Restoring the contents of the for@_;# variable
}

using {
    $_=uc$_for@_;
    say$foo,$bar,$buz;# content changed (global) variable, capitalized.
} $foo, $bar, $buz;# Unspecified variable arguments

say$foo,$bar,$buz;


2022-09-30 20:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.