• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 635
  • Last Modified:

@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.
0
hank1
Asked:
hank1
  • 2
1 Solution
 
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now