代码之家  ›  专栏  ›  技术社区  ›  chickeninabiscuit

Perl困境-分配和返回散列

  •  2
  • chickeninabiscuit  · 技术社区  · 15 年前

    我有一个实例变量properties,它的声明和实例化方式如下:

     $self->{properties}{$key1} = $value;
    

    我的理解是,这将声明properties字段,并将其设置为散列原语,其中包含一个键值对。

    我正在尝试为properties实例变量编写getter,它将返回散列:

    sub getProperties{
        my $self = shift;
    
        my %myhash = $self->{properties}; 
        return %myhash;
    }
    

    my %properties = $properties->getProperties();
    

    当我试图编译这个时,我得到:

    "Odd number of elements in hash assignment at 70..."
    
    line 70 being:    my %myhash = $self->{properties}; 
    
    2 回复  |  直到 15 年前
        1
  •  7
  •   Simon Whitaker    15 年前

    在这行代码中:

    my %myhash = $self->{properties};
    

    %myhash是散列,而$self->{properties}是散列 . 因此,您实际上返回了一个具有一个键/值对的散列,其中键是对散列的引用,而值是未定义的。

    如果确实要返回哈希,请执行以下操作:

    my %myhash = %{$self->{properties}};
    

    或者,返回哈希引用。这通常比返回散列更好,因为它不会生成原始散列的副本,因此随着散列变大,内存效率会更高。下面是它的外观:

    sub getProperties {
        my $self = shift;
        return $self->{properties};
    }
    

    然后在你的调用代码中而不是这个:

    my %properties = $properties->getProperties();
    $somevalue = $properties{'somekey'};
    

    执行以下操作:

    # getProperties returns a reference, so assign to a scalar
    # variable ($foo) rather than a hash (%foo)
    my $properties = $properties->getProperties();
    
    # Use -> notation to dereference the hash reference
    $somevalue = $properties->{'somekey'};
    
        2
  •  2
  •   RedGrittyBrick    15 年前

    不是 $self->{properties}

    $ perl t4.pl
    size -> 42
    

    t4.pl公司

    #!/usr/bin.perl
    use strict;
    use warnings;
    
    use t4;
    
    my $t4 = t4->new();
    my %hash = $t4->getProperties();
    for my $key (keys %hash) {
      print "$key -> $hash{$key}\n";
    }
    

    package t4;
    
    sub new {
      my $class = shift;
      my $self = {};
      $self->{properties}{size} = 42;
      bless ($self, $class);
    }
    
    sub getProperties {
      my $self = shift;
      my %myhash = %{$self->{properties}};
      return %myhash;
    }
    
    1;