【问题标题】:Perl: making an array ref out of a scalar variable inside of a hashPerl:用哈希内的标量变量制作数组引用
【发布时间】:2014-12-28 09:30:15
【问题描述】:

谁能告诉我如何从标量变量(相当于哈希引用)中创建数组引用?我到目前为止的代码是:

#! /usr/bin/perl
use strict;

my $index=0;
my $car={};

$car->{model}[$index]="Tesla";
my $texxt = $car->{model}[$index];
@{$texxt}=qw(1 2 3);

print "@{$texxt}";

这会产生以下错误: 在 test99.pl 第 8 行使用“strict refs”时,不能使用字符串(“Tesla”)作为 ARRAY 引用。

基本上,我正在尝试创建一个名为“@Tesla”的数组(或数组引用),该数组具有值(1 2 3)。

感谢您的帮助!

【问题讨论】:

  • 我在弄清楚你最终想要什么样的数据结构时遇到了一些麻烦。数组的散列?哈希的哈希?你能详细说明吗? c.f. perldsc.

标签: arrays perl data-structures hash


【解决方案1】:

如果 $texxt 是一个字符串(它不是一个哈希引用),你不能将它作为一个数组取消引用。不过,您可以为其分配一个匿名数组:

$texxt = 'Tesla';
$texxt = [qw[ 1 2 3 ]];

【讨论】:

    【解决方案2】:

    如果您想要一个带有名为“model”的键的散列,其中包含一个数组,其中第一个元素是“Tesla”,第二个元素是一个匿名数组(texxt 作为对它的快捷引用),那么这个会工作

    #! /usr/bin/perl
    use strict;
    
    my $index=0;
    my $car={};
    
    $car->{model}[$index]="Tesla";
    my $texxt = $car->{model} ;
    push @{$texxt} , [qw(1 2 3)];
    
    print ref eq "ARRAY" ? "@{$_}" : "$_ " for @{$texxt} ;
    

    输出:Tesla 1 2 3

    您可以使用Data::Printer 以格式良好的方式查看数据结构:

    use DDP;
    p $texxt;
    

    输出:

    \ [
        [0] "Tesla",
        [1] [
            [0] 1,
            [1] 2,
            [2] 3
        ]
    ]
    

    这可以帮助您可视化 perl 对您的数据所做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-13
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2011-07-26
      • 2016-06-06
      相关资源
      最近更新 更多