Adam C.
Adam C.

Reputation: 462

Cannot print array in the hash of another array

Please check the following code. I want to print array, but it only print the first item in array.

$prefix = 'ABC';
$search_pc_exclude = "PC1 PC2 PC3";

@exclude = split(/\s+/, $search_pc_exclude);
push @prefix, {"pre" => $prefix, "exc" => @exclude};

print $prefix[0]->{pre};
print $prefix[0]->{exc}; #why this is not array?

Upvotes: 0

Views: 94

Answers (1)

Linus Kleen
Linus Kleen

Reputation: 34622

The assignment actually is processed like this:

push @prefix, {"pre" => $prefix, "exc" => "PC1", "PC2" => "PC"}

Which gives you a hash with these keys. You need an array reference for that:

# This creates a copy of @exclude
push @prefix, {"pre" => $prefix, "exc" => [@exclude]}

Or:

# This creates a reference to @exclude. Any modifications to
# $prefix[0]->{exc} are actually modifications to @exclude
push @prefix, {"pre" => $prefix, "exc" => \@exclude}

Upvotes: 3

Related Questions