Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Why is my data structure wrong?

by George_Sherston (Vicar)
on Jun 24, 2002 at 23:52 UTC ( #176989=note: print w/replies, xml ) Need Help??


in reply to Why is my data structure wrong?

I think this is to do with an interesting feature of the x operator. The awfwy squoowy thing is happening right at the initialisation point:
my @data = ({}) x (3); print Dumper \@data;
produces
$VAR1 = [ {}, $VAR1->[0], $VAR1->[0] ];
... and not
$VAR1 = [ {}, {}, {}, ];
- if it had done that (for which you need @data = ({},{},{});) then the rest of the script would have done what you expected.

This tells something about how the x operator treats hashrefs (and arrayrefs for that matter) - it sets up the whole data structure so that *all* the data structures are whatever you set any one of them to, last time you set them.

It's instructive to put a last if $row == $n; at the end of your foreach my $row.... Then look at the contents of $report->{data} with
for (0..2) { print $report->{data}->[$_]->{foo}," => ", $report->{data}->[$_]-> +{bar},"\n"; }
- and goldarn if there isn't always the same thing in each of the three hashes, albeit a *different* same thing depending on what $n is.

Strikes me this could be a rather useful feature of the x operator... if only I can remember it until the right moment arises.

Thanks very much for this stimulating thread, by the way.


(I think part of the reason it was hard to work out what was going on is that (IMHO) local *MCVE::MCVE_NumRows    = sub { 3 }; should be local *MCVE::MCVE_NumRows    = sub { 4 }; - I think it's meant to be all the rows *including* the headers. Making it one short means that your sub is actually creating *one* hash in @data which is independent of the initialised hashes, and hence with a life of its own. That's why both the last *and* the second last key/value pairs in @rows are represented.)



George Sherston

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://176989]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2019-07-21 13:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?






    Results (8 votes). Check out past polls.

    Notices?