Unfortunately, the syntax isn't kind.
Defining Scalars, Arrays and Hashes.
$name = 'andrew' ;
# these 2 are the same, qw() is 'syntax sugar'
@names = qw( andrew john peter );
@names = ('andrew', 'john', 'peter');
%age = (
'andrew' => 20,
'peter' => 30,
'paul' => 17,
);
# note the outside hash uses (
# - but the inside hash uses {
%names = (
'andrew' => {
'age' => 20,
'height' => 1.76,
},
'peter' => {
'age' => 30,
'height' => 1.2,
'friends'=> ['andrew', 'paul'],
}
);
Scalars
$x = $names{'andrew'}{'age'};
# now $x = 20
$names{'andrew'}{'age'} = 35 ;
Arrays
Arrays are a bit more complex - use @{ } to access them and [ ] to set them
@x = @{ $names{'peter'}{'friends'} } ;
$names{'peter'}{'friends'} = [ 'bill', 'john', 'fred' ] ;
Hashes
Hashes are similar, use %{ } to access them and { } to set them
%hash = %{ $names{'andrew'} } ;
$names{'andrew'} = { 'age' => 20, 'height' => 1.76 } ;
Important Gotcha
When using the %hash = %{} and @array = @{} syntax, you are making a reference to the data, NOT a copy of it;
%hash = %{ $names{'andrew'} } ;
# %hash is a reference, change %hash and you change %names, and visa versa
%new_hash = %hash;
# now safe
No comments:
Post a Comment