如何确定Perl中变量的值是标量还是数组?

Dan*_*ral 7 perl

说我有这个:

my %hash;

$hash{"a"} = "abc";
$hash{"b"} = [1, 2, 3];
Run Code Online (Sandbox Code Playgroud)

以后我怎么能知道存储的是一个标量,如in "abc",还是数组,比如[1, 2, 3]

zig*_*don 14

首先,你的数组引用示例是错误的 - 你$hash{"b"}最终会得到一个标量值:你提供的列表的最后一个元素(在这种情况下为'c').

也就是说,如果您确实想要查看是否有标量或引用,请使用以下ref函数:

my %hash;

$hash{"a"} = "abc";
$hash{"b"} = [qw/a b c/];

if (ref $hash{"b"} eq 'ARRAY') {
  print "it's an array reference!";
}
Run Code Online (Sandbox Code Playgroud)

文件

  • 请注意,在OP的代码中,`$ hash {b}`最终成为''c'而不是'['a','b','c']`正如他想要的那样(或者我最初的预期为3)它). (2认同)

Cha*_*ens 8

首先,$hash{"b"} = qw/a b c/;将存储'c'$hash{"b"},不是一个数组,你可能意味着$hash{"b"} = [ qw/a b c/ ]; 将一个数组的引用存储中$hash{"b"}.这是关键信息.除了标量之外的任何内容在分配给标量时都必须存储为参考.有一个名为的函数ref将告诉您有关引用的信息,但如果引用已被祝福,它将向您提供对象类的名称.令人高兴的是,另一个名为的函数reftype总是返回它们的结构类型Scalar::Util.

#!/usr/bin/perl

use strict;
use warnings;

use Scalar::Util qw/reftype/;

my $rs  = \4;
my $ra  = [1 .. 5];
my $rh  = { a => 1 };
my $obj = bless {}, "UNIVERSAL";

print "ref: ", ref($rs), " reftype: ", reftype($rs), "\n",
    "ref: ", ref($ra), " reftype: ", reftype($ra), "\n",
    "ref: ", ref($rh), " reftype: ", reftype($rh), "\n",
    "ref: ", ref($obj), " reftype: ", reftype($obj), "\n";
Run Code Online (Sandbox Code Playgroud)