Solved

# @hash{@arr}=();  scalar into array then?

Posted on 2006-04-10
631 Views
Just want to get a handle on what's going on here.  This
answer was given in response to remove duplicate entires.

Here is the construct under question.

@hash{@arr}=();
@arr = keys %hash;

My logic ....

@hash{'key'} is one value.
@hash{qw(A B C D)} is my view of his @hash{@arr}

So, @a = (qw( A B C)) initializes an array
@a = {qw( A B C)} initializes a hash.

Then, along the same line (my lines), you could do this then

\$a = {qw(A B C)}

and then

foreach (@a) {
print;
}

and get a normal array from that?  Except it
doesn't work.  Why can't you force \$a into
an array.  @a = {list} forced @a into %a!

Strighten me out.  Thanks.
0
Question by:hank1

LVL 20

Accepted Solution

You were doing fine up til the line

@a = {qw( A B C)} initializes a hash.

While this is true, in a way, it isn't doing what you think. The construct

{qw(A B C) }

returns a reference to an anonymous hash and this reference is taken (even though you didn't write it precisely right) as the single element of the array @a. Data::Dumper will tell you that \@a looks like:

[
{
'A' => 'B',
'C' => undef
}
];

The constructions that you were given were using hash _slices_.

@hash{@arr} = ();

is a shortcut to initialize a hash (using the _slice_) with a set of keys and undefined values. For this purpose, the keys are all that is needed. In initializing the hash, duplicate keys replace any earlier instances of themselves, so to get a list of unique keys you do

@arr = keys %hash;

\$hash{'key'} is one value.
@hash{'key'} is a hash slice with only one value. It's equivalent to the simple \$hash{'key'} in many (most?) contexts. It's only when there's a multi-item list inside the braces that you must treat it as an array.

0

LVL 84

Expert Comment

@hash{qw(A B C D)} = ()
is equivalent to
(\$hash{A},\$hash{B},\$hash{C},\$hash{D}) = ();

@hash{'key'} = localtime;
is not equivalent to
\$hash{'key'} = localtime;
0

LVL 20

Expert Comment

Ozo's right, of course. I just had trouble thinking up the right counterexample (been out of practice). The contexts where @hash{'key'} will be taken as equivalent to \$hash{'key'} will fall on the right hand side of an equals sign, but it would be better to use scalars when you want scalars and arrays (or slices) where you want arrays.
0

LVL 1

Author Comment

Thanks both.
0

## Featured Post

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …