开发者

Best Way of Checking a String has one of Many Values in Perl?

I'm just in the middle of some Perl code and I found myself writing the monstrosity of a line of code shown below. Perl being so full of great little shortcuts, t开发者_JS百科here just has to be a better way than this right?

So - is there a better way to do this:

unless($config->{'case_transform'} eq 'NONE' || 
       $config->{'case_transform'} eq 'UPPER' ||
       $config->{'case_transform'} eq 'LOWER' ||
       $config->{'case_transform'} eq 'CAPITAL' ||
       $config->{'case_transform'} eq 'RANDOM')
{
    $config->{'case_transform'} = 'NONE';
}


my %good_value = map { $_ => 1 } qw( NONE UPPER LOWER CAPITAL RANDOM );

unless $good_value{$config->{case_transform}) {
    $config->{case_transform} = 'NONE';
}


Also available is the "Smart Match" operator ~~.

use 5.010;

$config->{'case_transform'} = 'NONE' 
    unless $config->{'case_transform'} ~~
        ( 'NONE', 'UPPER', 'LOWER', 'CAPITAL', 'RANDOM' );


unless ($config->{'case_transform'} =~ /^(NONE|UPPER|LOWER|CAPITAL|RANDOM)$/)
{
  ...
}


$config->{'case_transform'} = 'NONE' unless $config->{'case_transform'} =~ /^(?:UPPER|LOWER|CAPITAL|RANDOM)$/;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜