Perl uses sigils and (de)reference operators to show if your dealing with a ref.
The default for @arrays and %hashes is what I call their "list form", i.e. you always copy the content when assigning them:
DB<100> @a=(1,2,3) => (1, 2, 3) DB<101> @b=@a => (1, 2, 3) DB<102> $b[0]=42 => 42 DB<103> $a[0] # @a didn't change => 1
as you noticed $a[0] accesses the first element of @a, you need $ because $a[0] is a scalar and not an array.
But the behavior from Python is to default to the "reference form" for arrays and hashes and to the non-reference form for simple variables:
>>> a=[1,2,3] >>> b=a >>> b[0]=42 >>> a[0] 42
to achieve this behavior (e.g. to be able to nest data) you need references in Perl and refs are $scalars.
DB<104> $a=[1,2,3] => [1, 2, 3] DB<105> $b=$a => [1, 2, 3] DB<106> $b->[0]=42 => 42 DB<107> $a->[0] # original changed => 42
you need an explicit dereference operator -> to distinguish between the array @a and the referenced array in $a (yes they are different) ¹.
There is also a reference operator \ to get the reference of a variable.
This way the above example can be written
DB<108> \@a => [1, 2, 3] DB<109> $b=\@a => [1, 2, 3] DB<110> $b->[0]=666 => 666 DB<111> $a[0] # original changed => 666
There is an alternative way to dereference by prepending the intended sigil
DB<112> @$b => (666, 2, 3) # now a (list) not an [array-ref]
but you need to careful about precedence when dealing with nested structures.
There is more to say, but this should be enough for the beginning.
Please ask if you have further questions.
Cheers Rolf
( addicted to the Perl Programming Language)
1) There are no special sigils to denote a array_ref or a hash_ref in Perl. Which is unfortunate IMO cause one could avoid deref-operators this way! But the keyboard is already exhausted and things like €£¢ are difficult to type. I'm using a naming convention to mark them, e.g. $a_names for array_ref of names.
In reply to Re^3: Parsing an Array of Hashes, Modifying Key/Value Pairs (references)
by LanX
in thread Parsing an Array of Hashes, Modifying Key/Value Pairs
by librarat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |