Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Assigning an array to a hash

Tags:

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.

like image 515
Walt Stoneburner Avatar asked Mar 21 '11 23:03

Walt Stoneburner


People also ask

How do you handle an array and hash in Perl?

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 @ .

Can a hash value be an array?

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.

How do I create a hash from two arrays in Perl?

You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.

How do I push an array element in Perl?

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.


1 Answers

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).

like image 176
cjm Avatar answered Oct 19 '22 12:10

cjm