Highlights
All Snippets
Top 100 Snippets
Librarians
gbCodeLib

By Language
VB6
JavaScript
Perl
HTML
SQL
Java
DOS

GBIC >> Source Code >> Perl >> Snippet

10 Associative array


# associative array is a list of values indexed by strings (called keys)
# a regular array uses numbers for indexes, starting with 0

%myhash   = ( "Name" , "Gary" , "Age" , 51)    # key-value pairs
# assign list to hash

$myhash { 'Name' } = "Billy"           # assign single k-v pair
$a = $myhash { 'Name' }                # assign hash value to variable

@keylist    = keys @MyHash           # keys function retrieves all the keys of a hash
# random order
@valuelist = values @MyHash         # values function retrieves all values of a hash
# same order as keys
@reversehash = reverse @MyHash      # reverses key-value pairs (keys become values)
# duplicate values are dropped
$num_keys = scalar keys %hash       # find number of entries in a hash array

%hash = %myhash                     # copies entire %myhash into %hash2

Iterate over a hash

1.   foreach $key ( keys %MyHash )         # 'keys %myhash' creates list of all keys
{ print "$key :$MyHash{$key} \n " ; }       # print each key, then its value

2.   while ( ( $key , $vlaue ) = each %MyHash ) # goes through keys 1 at a time
{ print "$key :$MyHash{$key} \n " ; }       # print each key, then its value

delete a key:        delete $Hash { keyvalue }
remove all keys :     %Hash = ()

reverse the key / value pairs:     %reversehash = reverse %hasharray