我很尴尬地问这个问题,因为它是如此简单,但是我看不出有什么问题。我有一个例程可以清理IP范围的输入。这有点蛮力,但我不知道有更好的方法。我遇到的问题是,当我尝试删除仅保留'-'或''的内部空间时,因为条件块中的分隔符将单个前导和尾随空格括在分隔符中。如果我清理条件块外部的内部空间,则会正确删除这些空间。因此,在示例代码中,如果我在第1行上只有s / \ s + // g,它会正确清理;如果我在第2行和第3行上只有s / \ s + // g,则将空格括在方括号“-”中和','。到底是什么问题?
use feature qw(say);
use Data::Dumper qw(Dumper);
$input = " 192.168.1.1 198.168.1.254 ";
buildIpRangeArray ($input);
$input = " 192.168.1.1 , 198.168.1.254 ";
buildIpRangeArray ($input);
$input = " 192.168.1.1 - 198.168.1.254 ";
buildIpRangeArray ($input);
sub buildIpRangeArray {
say "input: $input";
$input = shift;
$input =~ s/^\s+//;
$input =~ s/\s+$//;
# $input =~ s/\s+//g; # Line 1.
# Works if this is uncommented
# and lines 2 and 3 are omitted
if ( index($input,' ') >= 0) {
$input =~ s/\s+/ /g; # this works
say "cleaned input 2: $input";
@range = split(/ /,$input);
say Dumper(@range);
}
elsif ( index($input,',') >= 0) {
$input =~ s/\s+//g; # Line 2
say "cleaned input 3: $input";
@range = split(/,/, $input);
say Dumper(@range);
}
elsif ( index($input,'-') >= 0) {
$input =~ s/\s+//g; # Line 3
say "cleaned input 4: $input";
@range = split(/-/, $input);
say Dumper(@range);
}
}
The output:
input: 192.168.1.1 198.168.1.254
cleaned input 2: 192.168.1.1 198.168.1.254
$VAR1 = '192.168.1.1';
$VAR2 = '198.168.1.254';
input: 192.168.1.1 , 198.168.1.254
cleaned input 2: 192.168.1.1 , 198.168.1.254
$VAR1 = '192.168.1.1';
$VAR2 = ',';
$VAR3 = '198.168.1.254';
input: 192.168.1.1 - 198.168.1.254
cleaned input 2: 192.168.1.1 - 198.168.1.254
$VAR1 = '192.168.1.1';
$VAR2 = '-';
$VAR3 = '198.168.1.254';
如果查看调试输出,则很明显发生了什么。让我们以逗号作为第二个输出块。
input: 192.168.1.1 , 198.168.1.254 cleaned input 2: 192.168.1.1 , 198.168.1.254 $VAR1 = '192.168.1.1'; $VAR2 = ','; $VAR3 = '198.168.1.254';
后输入,有一个检查,看看是否有一个空间' '
中的字符串中。在这里:
V
192.168.1.1 , 198.168.1.254
因此,代码永远不会到达elsif
逗号,
或破折号-
。您可以验证由于始终获得输入2,所以永远不要输入3或输入4。
下一步是清理空白,您可以在其中说出来。您可以用一个空格替换许多空白。那留,
在字符串中。现在,您在空白处分割,给您
ip
,
ip
总体而言,您的代码相当幼稚。重复很多,而您没有use strict
or use warnings
,这使得调试变得更加困难。根据如何使用此代码,我建议进行大量简化。
sub buildIpRangeArray {
my $input = shift;
say "input: $input";
my @range = grep {$_} split /[^0-9.]+/, $input;
say Dumper @range;
return;
}
我们分割了很多IP地址中不能包含的字符。这也很幼稚,因为它不会验证您是否具有实际的IP地址,但是您的代码也不会。它适用于任何数量的空格或任何定界符,即使它们是文本。我们需要grep
删除开头或结尾空格中出现的空字符串。""
Perl中的空字符串评估为false,因此grep
将其过滤掉。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句