下面是我想要做的一个小例子
#!/usr/bin/perl
$nums = "a,b,c,1,2,3";
@arr = split(",", $nums);
# If the contents of indexes 3 through 5 all match the correct syntax (any integer), print the message
if($arr[/^[3-5]{1}/] =~ /^[0-9]+/ ) {
print "Those elements in this array are all numbers";
}else{
print "\nsome of those elements are not numbers"
}这是否可以测试元素3到5是否都是整数?
发布于 2020-12-09 01:24:29
那行不通的。/^[3-5]{1}/将根据$_的值返回0或1,因此它只会检查$arr[0]或$arr[1]。
你可以使用
all { arr[$_] =~ /^[0-9]+\z/ } 3..5或
all { /^[0-9]+\z/ } @arr[3..5]all由List::Util提供。这可以改为使用grep。
!grep { arr[$_] !~ /^[0-9]+\z/ } 3..5或
!grep { !/^[0-9]+\z/ } @arr[3..5]发布于 2020-12-10 10:40:41
循环遍历感兴趣的数组元素,并在第一个非数字上删除标志,然后输出结果
use strict;
use warnings;
use feature 'say';
my $nums = 'a,b,c,1,2,3';
my @arr = split ',', $nums;
my $flag = 1; # Lets assume that all elements are numbers
for my $element ( @arr[3..5] ) {
$flag = 0 && last if $element !~ /^\d+/;
}
say $flag ? "all elements are numbers" :"not all elements are numbers";https://stackoverflow.com/questions/65203518
复制相似问题