2009/10/24 Shachar Shemesh <shac...@shemesh.biz>: > Noam Rathaus wrote: > > Shachar, > > { } in Perl are casting when they surround a value > And the second set of { } around the 'a' mean variable of Hash > > > > > Grumble grumble grumble....
not surprised as this is one of the funky places of Perl 5. > > Okay, I'm sorry for being difficult. I really couldn't find the answer in > the Perl documentation. > > I understand the second set of curly braces. I also, somewhat, understand > that the -> replaces the % (i.e. - reference dereferencing). What I'm not so > clear is what the first set of curly braces do (what do you mean by > "casting" - casting to what? How is that decided?). I'm also not clear on > why the surrounding round brackets are needed. I understand they are so this > will be a list context, but I don't understand why it's needed once I put a > @ to dereference the array. > > Thanks, > Shachar > > foreach my $elem (@{$ref->{a}}) err, I don't think that "casting" is the right word to use here. What {} does here is disambiguates the expression. Here is a table $x - scalar @x - array %x - hash $ra = \...@x reference to array sticking @ infront of the reference to an array dereferences it @x is the same as @$ra (you could also write and @{$ra} but it is not necessary) $x[1] is the same as $$ra[1] (element of array, replace @ by $ and attach the index) but it is ugly so it can also be written as $ra->[1] $rh = \%x reference to hash sticking % infront of the reference to a hash dereferences it %x is the same as %$rh (could be also written as %{$rh} but it is not necessary) $x{foo} is the same as $$fh{foo} which is the same as $fh->{foo} Now what if you have two dimensions: first dimension is a hash second dimension is an array. %h is a hash @something = ('foo'); $h{a} = \...@something; Which means print $h{a}[0]; # 'foo'; $ref = \%h; reference to hash %h is the same as %$ref $h{a} is the same as $$ref{a} or as $ref->{a} which is the reference to the array: \...@something sticking @ in front of it would dereference the array which would yield @$h{a} or @$$ref{a} @$ref->{a} which is the same as @something but it is not clear what does either of these mean (looking at the last one, @$ref could mean $ref is a reference to an array and that you are dereferencing @$ref and the resulting thingy is a hash ref) So we wrap the reference in a curly brace to make it clear that is a single variable: @{$h{a}} or @{$$ref{a}} @{$ref->{a}} which is the same as @{something} so the {} is basically around the "name' of the variable. Hope this helps Gabor _______________________________________________ Linux-il mailing list Linux-il@cs.huji.ac.il http://mailman.cs.huji.ac.il/mailman/listinfo/linux-il