in reply to Re: Why is my data structure wrong?
in thread Why is my data structure wrong?

No, that wasn't it, but you put me on the right path! You're correct that I had the wrong number of hashrefs, but changing the above line to my @data;, the output is correct. Thank you :)

Temp: '333 aaa' added to row 0 at test.pl line 39. Temp: '444 bbb' added to row 1 at test.pl line 39. Temp: '555 ccc' added to row 2 at test.pl line 39. $VAR1 = { 'data' => [ { 'foo' => '333', 'bar' => 'aaa' }, { 'foo' => '444', 'bar' => 'bbb' }, { 'foo' => '555', 'bar' => 'ccc' } ], 'headers' => [ 'foo', 'bar' ] };

Now, does anyone care to tell my po' self why this worked? I feel unusually dense today.

Update: Apparently, using the 'x' operator to populate an array with references will populate it with the same reference for every element, which apparently is the problem. My intent in populating the array with hashrefs was to ensure strong type checking:

my @foo = ([]); @{$foo[0]}{'one'}='uno'

The above code fails because you can't coerce an array into a hash.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: Re: Re: Why is my data structure wrong?
by japhy (Canon) on Jun 24, 2002 at 22:41 UTC
    Yes, using the x operator with references employs the same reference each time. Why? Because that's the most efficient way of doing it, I'd gather, regardless of whether you're using references or not!

    As proof, run these in the Perl debugger. (The first x is the 'display this data' instruction to the debugger.) You could also check the source code (pp.c) where the repeatcpy() C function or macro is employed.

    x map \$_, ("japhy") x 5; x ([]) x 5;

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      Why? Because that's the most efficient way of doing it, I'd gather

      Rather than some clever efficiency thing, I'd have thought it was simply because {} returns a scalar value. ('A') x 10 would give you 10 copies of the string 'A'. Similarly ( {} ) x 10 gives you 10 copies of a reference to a particular anonymous hash.

      What's a safe reference, I thought all references in Perl are safe ;-))

      -- Hofmator