arrays - 检测混合数组中的元素类型

标签 arrays perl ref scalar

我正在处理一些具有子例程的代码,该子例程包括一个数组引用作为参数之一。这个传入数组中的元素可以是小数组或字符串。

我想确定每个元素是什么类型以执行特定操作(即,如果元素是数组,则通过索引进一步深入研究,如果元素是字符串,则使用字符串)

我曾尝试使用 ref函数来查询每个数组元素。它似乎适用于数组元素,但如果元素是字符串,我期待 ref返回标量。然而ref()似乎什么都没有返回。我究竟做错了什么?我想ref()会返回一些东西。

下面是一些示例代码:

my @array = ("string1", 
             ["ele1_arraystr1", "ele1_arraystr2"], 
             "string2", 
             ["ele4_arraystr1", "ele4_arraystr2"], 
             "etc");
my $tmp;
&foobar( 30, 20, \@array);

sub foobar {
    my($var1, $var2, $array_ref) = @_;
    foreach $element (@$array_ref) {
        my $tmp = ref($element);
        print "Array element type: $tmp\n";
        if ($tmp eq 'ARRAY') {
            print "  ARRAY: $element->[1]\n";

        } elsif ($tmp eq 'SCALAR') {
            print "  SCALAR: $element\n";
        } else {
            print "  Unexpected type: $tmp\n";
       }
    }
 }

输出如下所示:
ARRAY element test:
Array element type: 
  Unexpected type: 
Array element type: ARRAY
  ARRAY: ele1_arraystr2
Array element type: 
  Unexpected type: 
Array element type: ARRAY
  ARRAY: ele4_arraystr2
Array element type: 
  Unexpected type: 

最佳答案

ref 如果其参数不是引用,则返回一个空字符串。文档说

Returns a non-empty string if EXPR is a reference, the empty string otherwise. The value returned depends on the type of thing the reference is a reference to.



以下列表包括 SCALAR , 是引用可以指向的类型。

因此,当它有一个字符串时,它会返回一个空字符串,该字符串的计算结果为 false。如果您确实知道它是 ARRAY或字符串,你可以做
if (ref($element) eq 'ARRAY') {
    # process the arrayref
}
else { 
    # process the string
}

更好地检查字符串 (false),就像您所做的那样,以便能够检测任何其他类型
my $ref_type = ref($element);
if ($ref_type eq 'ARRAY') {
    # process arrayref
}
elsif (not $ref_type) {  
    # process string
}
else { print "Got type $ref_type\n" }

关于arrays - 检测混合数组中的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443078/

相关文章:

c# - 为什么我在此代码中收到 IndexOutOfRangeException?

java - java中的列表字符串列表

perl - 如何在 Perl 中查找子列表模式的索引

reactjs - React-Table:在组件 ref 上调用 'getResolvedState()' 抛出异常

typescript - Vue Composition API - 使用 TypeScript 获取引用

java - 如何在放心中处理查询参数值中的特殊字符

c - 在数组中预读以预测 C 中的后续结果

regex - 编译动态创建的正则表达式的简洁方法

perl - PERL 中的模式匹配以句点 "."结尾

f# - 函数返回类型unit而不是类型ref