Wednesday, April 13, 2011

$, @, % in Perl variable declaration

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

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

%foo is a hash, this is like an array because it can hold more than one value, but hashes are keyed arrays. For example, I have a password hash called %password. This is keyed by the user name and the values are the user's password. For example:
$password{Fred} = "swordfish"; $password{Betty} = "secret";
$user = "Fred"; print "The Password for user $user is $password{$user}\n"; #Prints out Swordfish $user = "Betty"; print "The Password for user $user is $password{$user}\n"; #Prints out secret

No comments: