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

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.
LVL 1
hank1Asked:
Who is Participating?
 
jmcgOwnerCommented:
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
 
ozoCommented:
@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
 
jmcgOwnerCommented:
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
 
hank1Author Commented:
Thanks both.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.