How do you localize a number of global global variables without eval?

I ask this question because I finally solved the problem in which I tried to find equipment in a number of cases. I think this is pretty neat, so I do Q-and-A on this.

See, if I could use eval , I would just do this:

 eval join( "\n" , map { my $v = $valcashe{$_}; sprintf( '$Text::Wrap::%s = %s', $_ , ( looks_like_number( $v ) ? $v : "'$v'" ) ) } ); Text::Wrap::wrap( '', '', $text ); 

I even tried to be complicated, but it seems that local localizes the character to a virtual block, not a physical block. So this does not work:

 ATTR_NAME: while ( @attr_names ) { no strict 'refs'; my $attr_name = shift; my $attr_name = shift @attr_names; my $attr_value = $wrapped_attributes{$attr_name}; my $symb_path = "Text\::Wrap\::$attr_name"; local ${$symb_path} = $attr_value; next ATTR_NAME if @attr_names; Text::Wrap::wrap( '', '', $text ); } 

The same physical block, and I tested the package variables before and after installation, and they even showed the correct value in due time through the loop. But testing showed that only the last variable that passed through retained its value for the wrap call. Thus, the values โ€‹โ€‹remained localized until the end of the cycle.

I think the solution is neat - even if the secret is perl magick. But the end result is good because it means that I can wrap the legacy code that relies on variables with a batch scope and make sure that the values โ€‹โ€‹set are as short as possible.

+4
scope global-variables perl
source share
1 answer

Axman, you idiot! The set package is also a hash! It works:

 local @Text::Wrap::{ keys %wrapped_attributes } = \( values %wrapped_attributes ) ; 

This does the following:

  • It accesses a slice of the Text::Wrap character table array and returns named characters.
  • Since this is a symbol, not a scalar, so that perl can know the correct slot, you need to assign links. This is true for arrays and hashes, but we all know that their references are more common.
  • The syntax \( ... ) returns a link for each item in the list.

So, we localize each variable for each key in %wrapped_attributes , and we assign it a link for each value.

It is ugly and mysterious, and it is difficult to move it out of the way every time I need it, but with this I can pre-point and delay the localization to select the places where I can put Damien Conway, the proposed barbed wire and danger signs.

If I'm going to use it, it should just be ugly where I use it.

+6
source share

All Articles