tphyahoo has asked for the wisdom of the Perl Monks concerning the following question:

I just thought this was weird, interesting, and kind of nice... once you understand why perl behaves this way.
#@h{qw(a b c)} doesn't create an @h array. It sets 3 scalar values in + the %h hash. use strict; use warnings; use Data::Dumper; my (%h); #Note this works with use strict. There is no @h array. This sets $h +{a}, $h{b}, and $h{c}. @h{qw(a b c)} = (1, 2, 3); #Reset $h{b} just to make the point. $h{b} = 5; print '%h Hash:' . "\n"; print Dumper(\%h) . "\n\n"; #outputs: #%h Hash: #$VAR1 = { # 'c' => 3, # 'a' => 1, # 'b' => 5 # }; # # #%sorted Hash: #$VAR1 = {}; #

UPDATE: Thanks everyone. I should have read hash slice ? No thanks, I'm about to return... first.

Also, I just found that by doing my first phrase match using supersearch (on "list of values"). I had to ask for help, thanks castaway for explaining phrase match. You have to change the list separator to " and then search on "list of values".

  • Comment on @h{qw(a b c)} doesn't create an @h array. It sets 3 scalar values in the %h hash.
  • Download Code

Replies are listed 'Best First'.
Re: @h{qw(a b c)} doesn't create an @h array. It sets 3 scalar values in the %h hash.
by BrowserUk (Patriarch) on Mar 10, 2005 at 18:23 UTC

    Arrays are subscripted with []s not {}.

    @hash{...} = ...; is called a hash slice. See perlreftut.


    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.

      ...which is related to array slices:

      my %hash = ( 'a' => 'A', 'b' => 'B', 'c' => 'C', ); my @array = qw( d e f ); print(join(', ', @hash{'a', 'b'} ), "\n"); # A, B print(join(', ', @array[0, 1] ), "\n"); # d, e
Re: @h{qw(a b c)} doesn't create an @h array. It sets 3 scalar values in the %h hash.
by Mugatu (Monk) on Mar 10, 2005 at 20:37 UTC

    More generally, this shows off the fact that the sigil does not represent the variable type, it represents the value type. The variable type is determined by other things. In this case, [] vs {} (as BrowserUk explained).

    Thus, when you want a single value from an array, you say $array[...]. When you want a list of values, you say @array[...]. Likewise with a hash: $hash{...} vs @hash{...}.