Nano's Blog

01/06/2010

Hash Element Access

Filed under: programming — Tags: — nano @ 06:28
#!C:\Perl\bin\perl.exe
use strict;
use warnings;

# declare a new hash
my %family_name;

# Initial hash.
# Compared to array access, we use curly braces instead of square brackstes around the subscript(key)
$family_name{"fred"} = "flintstone";
$family_name{"barney"} = "rubble";

# print the Values
print $family_name{"fred"};
print "\n";
print $family_name{"barney"};
print "\n";

# the hash key maybe any expression. not just the literal strings and simple scalar variables
my $foo = "bar";
print $family_name{ $foo . "ney" };  # prints "rubble"
print "\n";

# Stuff $person and as the Keys for hash.
foreach my $person (qw< barney fred >) {
  print "I've heard of $person $family_name{$person}.\n";
}

Output

flintstone
rubble
rubble
I've heard of barney rubble.
I've heard of fred flintstone.

- from Learning Perl 5E

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress