Monday, August 21, 2006

[Perl] Basic Hash operations

Source:

Perl Howto --> Hash by Alex BATKO <abatko AT cs.mcgill.ca>

Codes:

my %hash = ();
%hash = ( 'key1', 'value1', 'key2', 'value2', 'key3', 'value3');
%hash = ( 'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3' );
$hash{ $key } = $value;
my %hash_copy = %hash;

if exists $hash{ $key };
if defined $hash{ $key };
if $hash{ $key };

delete $hash{$key}

# size of a hash
my $hash_size = keys( %hash );

# Process each key of the hash
while ( my ($key, $value) = each(%hash) ) { print "$key => $value\n"; }
for my $key ( keys %hash )
{
my $value = $hash{$key}; print "$key => $value\n";
}

For Hash references:

my $hash_ref = 0;
$hash_ref->{ $key } = $value; # $hash_ref is a reference of a hash.
delete $hash_ref->{$key};

# size of a hash
my $hash_ref_copy = $hash_ref;
my $hash_ref_size = 0; $hash_ref_size += scalar keys %$hash_ref;

# Process each key of the hash
while ( my ($key, $value) = each(%$hash_ref) ) { print "$key => $value\n"; }

No comments: