in reply to Getting different anonymous arrays

I thought I would give it a test.
Could someone explain this?
use Data::Dumper; use strict; my @array; my %array; @array = qw( a b c d ) ; @array{ @array } = ( [ @array ] ) x @array ; print Data::Dumper->Dump([\%array], ["*array"]); __OUTPUT__ %array = ( 'c' => [ 'a', 'b', 'c', 'd' ], 'a' => $array{'c'}, 'b' => $array{'c'}, 'd' => $array{'c'} );
I don't get it either!
perl -v This is perl, v5.8.0 built for MSWin32-x86-multi-thread (with 1 registered patch, see perl -V for more detail) Copyright 1987-2002, Larry Wall Binary build 806 provided by ActiveState Corp. http://www.ActiveState. +com Built 00:45:44 Mar 31 2003 ---snip---

--

flounder

Replies are listed 'Best First'.
Re: Re: Getting different anonymous arrays
by broquaint (Abbot) on Sep 08, 2003 at 18:59 UTC
    ( [ @array ] ) x @array ;
    Make N copies of [ @array ]
    @array{ @array } = ( [ @array ] ) x @array ;
    Do the hash assign of the N copies. This is all obvious so far, now for the trickier bit, the output
    %array = ( 'c' => [ 'a', 'b', 'c', 'd' ], 'a' => $array{'c'}, 'b' => $array{'c'}, 'd' => $array{'c'} );
    Unusual, you say, that the key 'c' should get 'the original' and the rest get copies, but if we look at the ordering of the keys this makes sense
    shell> perl -le 'print keys %{{map {$_=>1} qw/a b c d/}}' cabd
    So as you may have guessed by now Data::Dumper's output shows that 'c' just happens to look like its got 'the original' due to the ordering of the hash. In reality they all point to the same anonymous array.
    HTH

    _________
    broquaint

Re: Re: Getting different anonymous arrays
by MidLifeXis (Monsignor) on Sep 08, 2003 at 16:57 UTC

    This is just a freeze/thaw way of getting back a structure which points at the same arrayref. If you built it like this:

    %array = ( 'a' => ['a','b','c','d'], 'b' => ['a','b','c','d'], 'c' => ['a','b','c','d'], 'd' => ['a','b','c','d'] );

    you would have four different anonymous arrays, not four refencences to the same array, as the original code created.

    Not sure if this answered your question, or if I even understood it, but there you go :).

      I just thought it was weird that the anonymous array was definded as the value of the hash key 'c' and all the rest of the hash keys have a value of its reference. It seems to me that the hash key 'a' would have been defined first and the other keys would have the value of its reference. I guess it doesn't matter -- they all point to the same anonymous array reference.

      I see what happens. if I add this line to my original program:

      print join ",", keys %array;
      I get an output of:
      c,a,b,d
      So Data::Dumper must just take the first key it gets from keys point it to the anonymous array reference and then have the rest of the keys point to it. That makes sense. You learn something new every day.

      --

      flounder