通过引用

时间:2015-12-28 12:30:33

标签: arrays perl hash reference

我想通过子函数修改哈希数组,因此我想通过引用切换数组,在子函数中去引用并进一步修改它。

在此修改之后,数组应立即保存修改后的值,我不想明确地返回修改后的哈希值(想要在原始数组上工作)。

不幸的是,我没有成功。有许多关于访问哈希数组引用的网络提示,但我找不到一个操纵数组的提示。

my @array_of_hashes = ( {name => "Alice"}, 
                        {name => "Bob"} );
my $myhashref = \%{$array_of_hashes[0]};  # This holds a ref to {name=>"Alice"}
my %myhash = %{$myhashref};   # De-reference, shall be the Hash to work on
print $myhash{name} . "\n";   # This shows Alice
$myhash{age}=32;     # Want to add 'age' to the Alice Hash, does not work

此修改后的哈希不会显示{age}。当您查看@array_of_hashes print Data::Dump::dump(@array_of_hashes)时,$myhash{age}=32;行对@array_of_hashes没有影响。

我如何移交对例如@array_of_hashes函数的第一个元素以及如何在函数中取消引用它以便能够修改@array_of_hashes中的哈希值?

2 个答案:

答案 0 :(得分:2)

你说:我想用子函数修改哈希数组

如果我理解正确,可以使用以下内容:

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();
        /* This is here only to simplify development and display here */

        $delimiter=isset( $_POST['delimiter'] ) ? $_POST['delimiter'] : '|';

        /* process form submission: for testing purposes just echo out data sent */
        foreach( $_POST as $field => $value ) {
            if( $field!='delimiter' ){
                if( is_array( $value ) ) echo 'Array values: '.$field.'='.rtrim( str_replace( $delimiter, ',', implode( ' ', $value ) ), ',' ).'<br />';
                else echo 'String value: '.$field.'='.trim( str_replace( $delimiter, '', $value ) ).'<br />';
            }
        }

        exit();
    }
?>

以上产生了例如:

use 5.014;
use warnings;
use Data::Dumper;

my @aoh = (
    {name => "Alice"}, 
    {name => "Bob"}
);
do_some(\@aoh); #pass arrayref
$aoh[1]->{text} = 'huhu';
say Dumper \@aoh;
say "$aoh[1]->{name} has age $aoh[1]->{age} and says $aoh[1]->{text}";

sub do_some {
    my $ar = shift;
    for my $hr (@$ar) { #for each array element
        $hr->{age} = int rand 100;
    }
}

# however (IMHO)
# using arrayref from the beginning is more cleaner
my $aohr = [
    {name => "Alice"}, 
    {name => "Bob"}
];
do_some($aohr);
$aohr->[0]->{text} = 'juju';
say Dumper $aohr;
say "$aohr->[0]->{name} has age $aohr->[0]->{age} and says $aohr->[0]->{text}";
#could use the shortened form
#say "$aohr->[0]{name} has age $aohr->[0]{age} and says $aohr->[0]{text}";

答案 1 :(得分:0)

您在创建阵列时已经为每个哈希创建了一个引用。然后你将散列放大并将其分配给新的散列变量。

my %myhash = %{$myhashref};   # De-reference, shall be the Hash to work on

所以你现在有了一个新的哈希值,它被创建为alice哈希的副本。但是新的哈希和alice哈希是分开的。然后你修改新的哈希工作正常但它不会反映在alice哈希中,因为它们是分开的。相反,你应该修改现有的散列引用。例如,请尝试以下。

use strict;
use warnings;
use Data::Dumper;

my @array_of_hashes = ( {name => "Alice"}, 
                        {name => "Bob"} );
print $array_of_hashes[0]->{'name'}, "\n";#this shows alice
$array_of_hashes[0]->{'age'}=32;     # Want to add 'age' to the Alice Hash, does not work


print Dumper \@array_of_hashes;