Wednesday, April 13, 2011

Understanding Perl Variables: Scalars ($), Arrays (@), and Hashes (%)


Scalar Variables ($)

$foo is a scalar variable. It can hold a single value, which can be a string, a number, etc.

Array Variables (@)

@foo is an array. Arrays can hold multiple values, and you can access these values using a numeric index. For example, $foo[0] is the first element of the array, and $foo[1] is the second element. (Arrays in Perl usually start with an index of zero).

Hash Variables (%)

%foo is a hash. This is similar to an array because it can hold more than one value, but hashes are keyed arrays. Instead of numeric indexes, you use strings (keys) to look up values.

For example, if I have a password hash called %password, it can be keyed by the username, and the values are the users' passwords:
Perl
use strict;
use warnings;

# Declare the hash
my %password;

# Assign values using the string keys 'Fred' and 'Betty'
$password{Fred}  = "swordfish"; 
$password{Betty} = "secret"; 

# Look up and print Fred's password
my $user = "Fred"; 
print "The password for user $user is $password{$user}\n"; # Prints: swordfish 

# Look up and print Betty's password
$user = "Betty"; 
print "The password for user $user is $password{$user}\n"; # Prints: secret

No comments: