> I am having problem with array and Hash data structure. Example is show 
below:

#CODE 1
my @list;
my %this;
$this{x} = 1;
$this{y} = 2;
$this{z} = 3;
$this{Z} = 4;

Better (maybe):
my %this = (
        x => 1,
        y => 2,
        z => 3,
        Z => 4,
      )


push @list, %this;
> The last line does not work according to what I want it to do.
> And instead, @list now contains:
$list[0] = 'x';

The problem here is the list context 'unrolls' the "this" hash to 
(x,1,y,2,z,3,Z,4)

so it's a simple list pushed into the array.


>My intention above is to have variable @list as an array of hash, ie:
$list[0]{x}
$list[0]{y}
$list[0]{z}
$list[0]{Z}

This works:
$list[0]{x} = 1;
$list[0]{y} = 2;
...
print("$_: ", $list[0]->{$_}, "\n") foreach keys %{$list[0]};



> I have resorted to:
@list[ scalar @list ] = %this;
> which I find not so "elegant"...

Er, that doesn't work for me. For one thing "scalar @list" will be zero on 
the LHS of the assignment, but it'll be 1 afterwards.  What you want is an 
"anonymous" hash as the element so
$list[0] = {
       x => 1,
       y => 2,
       z => 3,
       Z => 4,
};

Note curly brackets, or
my %this = (
       x => 1,
       y => 2,
       z => 3,
       Z => 4,
);
my @list;
@list[ 0 ] = \%this;

or:
push @list, \%this;


> Secondly, is there a way to not use the has variable %this above?
> ie, something like
push @list, {x=>1,y=>2,z=>3,Z=>4};

seems to work here:
my @list;
push @list, {x=>1,y=>2,z=>3,Z=>4};
print("k $_: ", $list[0]->{$_}, "\n") foreach keys %{$list[0]};

> And lastly, as I try to pop it out:
%this = pop @list;
printf "%d %d %d %d\n", $this{x}, $this{y}, $this{z}, $this{Z};

>it wont work. I am getting zeroes/blank on the hashes. Why?

Because you're getting back a "reference" to the anonymous hash now, in 
this - s/b
my $this = pop @list;
printf "%d %d %d %d\n", $this->{x}, $this->{y}, $this->{z}, $this->{Z};

> How should I write it "correctly" again?

You need to use the reference (the most Perl-ish method) or un-roll the 
reference on the RHS so it can assign back into the by "casting" it as a 
hash again:
my %this = %{pop @list};
printf "%d %d %d %d\n", $this{x}, $this{y}, $this{z}, $this{Z};

a

----------------------
Andy Bach
Systems Mangler
Internet: andy_b...@wiwb.uscourts.gov
Voice: (608) 261-5738, Cell: (608) 658-1890

"If Java had true garbage collection, most programs would delete 
themselves upon execution."
Robert Sewell.
_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to