lazurwol has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I am trying to use copy a list from a reference hash. I am passing the hash to a subroutine as a reference.
I can copy individual items from the hash without a problem but I cannot figure out how to copy the list contained in the refence.
This is what I have tried.


my %Point = ('E' => [0,1,2], 'ID' => 'X30Y30VX11VY15E15'); &SomeRoutine(\%Point); sub SomeRoutine { $P = shift; $id = $$P{'ID'}; @e = $@{$P{'E'}};



When I use this code the copy of the list returns back the following error:
Use of uninitialized value in hash element

Replies are listed 'Best First'.
Re: How to copy an list from a reference hash?
by davido (Cardinal) on Nov 30, 2004 at 22:24 UTC

    Try this:

    sub SomeRoutine { my $href = shift; my $id = $href->{'ID'}; my @e = @{$href->{'E'}}; #........ }

    Dave

Re: How to copy an list from a reference hash?
by Velaki (Chaplain) on Nov 30, 2004 at 22:36 UTC

    Running this with use strict reveals a helpful error:

    Global symbol "%P" requires explicit package name
    in the line containing @e = $@{$P{'E'}};

    $P is a reference, whereas $P{'E'} refers to a simple hash variable, called %P. Since you wish to use the reference, you will need to dereference it back to the hash %$P, using either:

    $$P{'E'}
    or
    $P->{'E'}

    Now, since that is also a reference to an array, you will need to dereference that with;

    @{$P->{'E'}}
    So the line which strict reports in error should be:
    @e = @{$P->{'E'}};

    Hope that helped,
    use strict; # it's the right thing to do
    -v
    "Perl. There is no substitute."
Re: How to copy an list from a reference hash?
by injunjoel (Priest) on Nov 30, 2004 at 22:26 UTC
    Greetings all,
    What about this?
    sub SomeRoutine { $P = shift; $id = $P->{'ID'}; @e = @{$P->{'E'}}; }

    Personally I prefer the arrow notation for dereferencing. It just make more visual sense to me.
    I hope that helps,

    -InjunJoel
    "I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo
Re: How to copy an list from a reference hash?
by jimbojones (Friar) on Nov 30, 2004 at 22:28 UTC
    The arrow is your friend

    use strict; use warnings; my %Point = ('E' => [0,1,2], 'ID' => 'X30Y30VX11VY15E15'); &SomeRoutine(\%Point); sub SomeRoutine { my $hashref = shift; my $id = $hashref->{'ID'}; my @e = @{$hashref->{'E'}}; print $id, "\n"; print @e, "\n"; } __DATA__ X30Y30VX11VY15E15 012
    HTH,

    -j