0

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?

1 Answer 1

3

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}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Linus! But after changing it to \@exclude, I still could not print it (print $prefix[0]->{exc};), but got "ARRAY(0x9e2b368)".
Nevermind. I figured it out. I need to dereference it first (ie, $arr = $prefix[0]->{exc}; @arr = @$arr;) Thanks again!
That's because $prefix[0]->{exc} is an array reference, which you need to dereference! Use print @{ prefix[0]->{exc} } to print the array...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.