Perl Tutorials - Herong's Tutorial Examples - v6.01, by Dr. Herong Yang
Using Hash Variables
This section describes how a hash variable can be assigned with a list value. Hash elements are referred by key subscription notation as scalar expressions, like $identifier{'key'}. An unassigned hash variable contains the (undef) value.
Hash variables can be used in a Perl script under these rules:
Here are some examples of hash variable assignment operations with list value constructors:
%messages = 'hello'; %primes = 3,5,7,11; %vacations = 'Mon','Tue','Wed'; %vacations = ('Mon','Tue','Wed'); %vacations = (Mon,Tue,Wed); %menu = 'Mon',2,'Apple'; %dates = 'Jan',31,'Feb',28,'Mar',31; %prices = ('Milk',1.99,'Coke',0.99,'Bread',1.49);
Here is a Perl tutorial script on how to use hash variables:
#- HashVariable.pl #- Copyright (c) HerongYang.com. All Rights Reserved. # %siteRanks; # Undefined print(%siteRanks, "\n"); %siteRanks = ("herongyang.com", 4, "perl.org", 6, "google.com", 9); print(%siteRanks, "\n"); # Defined now %siteRanks = ("herongyang.com"=>4, "perl.org"=>6, "google.com"=>9); print(%siteRanks, "\n"); # Using => operator $myRank = $siteRanks{"herongyang.com"}; print($myRank, "\n"); # Refers to a value by key $siteRanks{"google.com"} = 10; # Updates a value by key print($siteRanks{"google.com"}, "\n"); $siteRanks{"yahoo.com"} = 8; # Adding a new key-value pair print($siteRanks{"yahoo.com"}, "\n"); print ("undef", "\n") if ($siteRanks{"xyz.com"} == undef); # Undefined key
Here is the output of the tutorial script:
herongyang.com4google.com9perl.org6 herongyang.com4google.com9perl.org6 4 10 8 undef
Table of Contents
►Data Types: Values and Variables
Variables - Scalar, Array and Hash
"undef" Value and Undefined Variables
Expressions, Operations and Simple Statements
Name Spaces and Perl Module Files
Hard References - Addresses of Memory Objects
Objects (or References) and Classes (or Packages)
Typeglob and Importing Identifiers from Other Packages
String Built-in Functions and Performance
File Handles and Data Input/Output
Open Directories and Read File Names
File System Functions and Operations
Socket Communication Over the Internet
XML::Simple Module - XML Parser and Generator
SOAP::Lite - SOAP Server-Client Communication Module
Perl Programs as IIS Server CGI Scripts
CGI (Common Gateway Interface)
XML-RPC - Remote Procedure Call with XML and HTTP
RPC::XML - Perl Implementation of XML-RPC
Integrating Perl with Apache Web Server
CGI.pm Module for Building Web Pages
LWP::UserAgent and Web Site Testing
Converting Perl Script to Executable Binary