Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.2 Variables

We have seen that each of the different native data types in Perl has a special character that identify that the variable is of that type. Hashes always start with a %.

Accessing a hash works very similar to accessing arrays. However, hashes are not subscripted by numbers. They can be subscripted by an arbitrary scalar value. You simply use the {} to subscript the value instead of [] as you did with arrays. Here is an example:

use strict; my %table; $table{'schmoe'} = 'joe'; $table{7.5} = 2.6;

In this example, our hash, called, %table, has two entries. The key 'schmoe' is associated with the value 'joe', and the key 7.5 is associated with the value 2.6.

Just like with array elements, hash elements can be used anywhere a scalar variable is permitted. Thus, given a @hash{%table} built with the code above, we can do the following:

print "$table{'schmoe'}\n"; # outputs "joe\n" --$table{7.5}; # $table{7.5} now contains 1.6

Another interesting fact is that all hash variables can be evaluated in the list context. When done, this gives a list whose odd elements are the keys of the hash, and whose even elements are the corresponding values. Thus, assuming we have the same %table from above, we can execute:

my @tableListed = %table; # @tableListed is qw/schmoe joe 7.5 1.6/

If you happen to evaluate a hash in scalar context, it will give you undef if no entries have yet been defined, and will evaluate to true otherwise. However, evaluation of hashes in scalar context is not recommended. To test if a hash is defined, use defined(%hash).




 
 
  Published under the terms of the GNU General Public License Design by Interspire