-1

i tried several hours to store a sub array into an object and failed. maybe someone of you can show me how to store a deep copy with perl. sry i dont know if this question is clear, but should be easy to solve...

here the example.

here the object class

package obj;

use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);

sub new(\@){
    my $class=shift;
    my $this={};
    $this->{"array"}=shift;
    return bless($this,$class);
}

sub getArray(){
    my $this=shift;
    return $this->{"array"};
}

and the test class

use strict;
use warnings;
use obj;

my @a=(1,2);
push @a,3;
my $ob=obj->new(\@a);
@a=();
print @{$ob->getArray()};

this returns nothing - does not shift dereference the array?

so how to do this?

thx

pyr0
  • 377
  • 1
  • 14

1 Answers1

0

Deference what array? The only array involved in the shift is @_? $_[0] is a scalar, not an array.

A (shallow) array copy is done using:

@dst = @src;

so you want

@{ $this->{"array"} } = @{ shift };

If you truly want an deep copy (though there's no need for it in your example), use

use Storable qw( dclone );

$this->{"array"} = dclone(shift);
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    or do a shallow copy by: `$this->{'array'} = [ @{ shift } ]` – ysth Oct 18 '12 at 05:28
  • if i do this, the output will become a scalar and and it returns only the first array element 1. i think that a deep copy is necessary because i overwrite @a=(). so the referenced array is gone. use Storable qw( dclone ); do what i want. thx – pyr0 Oct 18 '12 at 09:17
  • @pyr0, I don't know if you are referring to my code or ysth, but neither copies a single element of the array. – ikegami Oct 18 '12 at 14:55