简体   繁体   English

将数组存储到Perl哈希中的正确语法是什么?

[英]What is the proper syntax for storing an array into a Perl hash?

I'm creating a new object like this: 我正在创建一个像这样的新对象:

TestObject->new(@array1, @array2)

My new method looks like this: 我的new方法如下所示:

sub new {
  my $class = shift;
  my $self = {};

  my $self->{Array1} = shift;
  my $self->{Array2} = shift;

  bless($self, $class);

  return $self;
}

As a simple test to access the data, I'm trying this, and then once I get it working, I can build more meaningful logic: 作为访问数据的简单测试,我正在尝试这种方法,然后一旦它开始工作,我可以构建更有意义的逻辑:

sub mymethod {
  my $self = shift;
  my $param = shift;

  my $array1Value = shift(my $self->{Array1});
  my $array2Value = shift(my $self->{Array2});

  print $array1Value." ".$array2Value;
}

But when I call mymethod , I get this error: 但是当我调用mymethod ,出现此错误:

Type of arg 1 to shift must be array (not hash element) at Tests/MyObject.pm line 21, near "})"

Suggestions? 有什么建议吗? I read this page on Perl data structures , but they don't have examples for creating a hash of arrays using arguments to a method using shift . 在Perl数据结构上读了这个页面 ,但是他们没有使用shift方法创建数组哈希的示例。 So my problem might be there. 所以我的问题可能在那里。

When you pass arrays as parameters, they are flattened. 当您将数组作为参数传递时,它们将被展平。 You can pass references to them. 您可以将引用传递给它们。 See perlsub perlsub

#!/usr/bin/env perl

package foo;

sub new {
    my $class = shift;
    my $self = {};

    $self->{Array1} = shift;
    $self->{Array2} = shift;

    bless($self, $class);

    return $self;
}

sub mymethod {
  my $self = shift;
  my $param = shift;

  my $array1Value = shift( @{$self->{Array1}} );
  my $array2Value = shift( @{$self->{Array2}} );

  print "$array1Value $array2Value\n";
}

package main;

my @a = ( 0, 1, 2);
my @b = ( 3, 4, 5);
my $o = new foo( \@a, \@b );;
$o->mymethod;

you have to use pointers to arrays, not arrays in this case: 您必须使用指向数组的指针,在这种情况下,不能使用数组:

  TestObject->new([@array1], [@array2])

and then later 然后再

my $array1Value = shift(@{$self->{Array1}});

You're shifting an arrayref instead of an actual array. 您正在移动arrayref而不是实际的数组。

The syntax ytou're probably looking for is: ytou可能正在寻找的语法是:

my $array1Value = shift @{ $self->{Array1} };
my $array2Value = shift @{ $self->{Array2} };

Note how the array is dereferenced using @ . 注意如何使用@取消引用数组。

you need to derefernece the array ref: 您需要取消引用数组引用:

@{$self->{Array2}}

By the way if you are using OO I emphatically suggest you look into Moose . 顺便说一句,如果您使用的是OO,我强烈建议您研究Moose It will make your life much easier! 这将使您的生活更加轻松!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM