2013-04-05 99 views
1

我可以操作单个数组元素,并将该数组的引用添加为散列中的值。简单。例如,这达到了预期的效果:Perl - 转换匿名数组

# split the line into an array 
my @array = split; 

# convert the second element from hex to dec 
$array[1] = hex($array[1]); 

# now add the array to a hash 
$hash{$name}{ ++$count{$name} } = \@array; 

我的问题:使用匿名数组可以做同样的事情吗?我可以通过执行以下操作来关闭它:

$hash{$name}{ ++$count{$name} } = [ split ]; 

但是,这不会操纵匿名数组的第二个索引(将十六进制转换为十进制)。如果可以做到,怎么样?

回答

4

你所要求的是这个

my $array = [ split ]; 

$array->[1] = hex($array->[1]); 

$hash{$name}{ ++$count{$name} } = $array; 

但是,这可能不是你的意思。

此外,而不是使用顺序编号的哈希键,你可能会更好使用数组的哈希值,这样

my $array = [ split ]; 

$array->[1] = hex($array->[1]); 

push @{ $hash{$name} }, $array; 

您需要一种方法来访问数组说要修改什么,但你可以修改它后推到散列,像这样:

push @{ $hash{$name} }, [split]; 
$hash{$name}[-1][1] = hex($hash{$name}[-1][1]); 

虽然这真的不是很好。或者你可以

push @{ $hash{$name} }, do { 
    my @array = [split]; 
    $array[1] = hex($array[1]); 
    \@array; 
}; 

甚至

for ([split]) { 
    $_->[1] = hex($_->[1]); 
    push @{ $hash{$name} }, $_; 
} 
+0

感谢信鲍罗廷。我想我的问题是 - '$ array'也可以匿名吗?我现在可以看到它不可能。我也会执行你的建议。干杯。 – Steve 2013-04-05 01:20:57

+0

$ array是对匿名数组的引用;这有帮助吗?你可以做$ hash {$ name} {++ $ count {$ name}} = map [$ _-> [0],hex($ _-> [1]),@ $ _ [2。 。$#$ _]],[split];'但是这将是愚蠢的 – ysth 2013-04-05 02:46:12

+1

这是这个主题的另一种变化:'$ hash {$ name} {++ $ count {$ name}} =(map {$ _ - > [1] = hex($ _-> [1]); $ _}([split]))[0];' – imran 2013-04-05 02:49:32