This syntax works:
$b{"x"} = [1,2,3]; pp %b; # Displays ("x", [1, 2, 3])
But I need to be able to dynamically create the array's contents and assign it later. This does not work; help, what's the obvious part I'm missing?
@a = [1,2,3]; $b{"x"} = @a; pp %b; # Shows up as ("x", 1) ... not what I want or expected.
Tried these variations, too.
$b{"x"} = [@a]; # ("x", [[1, 2, 3]]) ...close $b{"x"} = \@a; # ("x", [[1, 2, 3]]) $b{"x"} = [\@a]; # ("x", [[[1, 2, 3]]]) $b{"x"} = %a; # ("x", 0) $b{"x"} = $a; # ("x", undef) $b{"x"} = [$a]; # ("x", [undef]) $b{"x"} = @{@a}; # ("x", 0)
And, ideally, I'd like to be able to get the array back out later as an array.
To assign some values to the array, just enclose them in parentheses. You can retrieve them with the index number. Notice how the @ changed to a $ for the print statement; I wanted it to return a scalar, a single thing, not a list of things. If you want to do things to the whole array, use the @ .
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.
Perl | push() Function push() function in Perl is used to push a list of values onto the end of the array. push() function is often used with pop to implement stacks. push() function doesn't depend on the type of values passed as list.
The part you're missing is that @a = [1,2,3]
doesn't make an array with 3 elements. It makes an array with one element which is an arrayref.
You meant @a = (1,2,3)
.
To assign that array to a hash element, you'd use either $b{"x"} = [@a]
or $b{"x"} = \@a
, depending on what you're trying to do. [@a]
makes a new arrayref containing a copy of the current contents of @a
. If the contents of @a
change after that, it has no effect on $b{x}
.
On the other hand, \@a
gives you a reference to @a
itself. If you then change the contents of @a
, that will be visible in $b{x}
(and vice versa).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With