2014-11-01 63 views
1

任何人都可以請讓我知道如何從一個標量變量(等同於散列引用)中創建一個數組ref?我到目前爲止的代碼是:Perl:在散列內部的標量變量中創建一個數組ref

#! /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。

基本上我試圖讓一個名爲「@Tesla」的值(1 2 3)的數組(或數組參考)。

感謝您的幫助!

+0

我在確定你最終想要什麼樣的數據結構時遇到了一些麻煩。數組哈希?哈希哈希?你能詳細說明嗎? * c.f. * ['perldsc'](http://perldoc.perl.org/perldsc.html)。 – 2014-11-01 05:24:34

回答

1

:您可以指定一個匿名數組分配給它,雖然(和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做您的數據。

+0

謝謝。這有助於 - 我將它實現爲散列或數組... – Hans 2014-11-01 18:56:47

0

如果$ texxt是一個字符串(它不是散列引用),那麼不能將它解引用爲一個數組。如果你想用一個所謂的「模式」鍵包含數組與「特斯拉」作爲第一個元素,一個匿名數組作爲第二個元素的哈希

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