Perl Tutorials - Herong's Tutorial Examples - v6.01, by Dr. Herong Yang
"undef" Value and Undefined Variables
This section describes what is the 'undef' value and what is an undefined variable. A scalar, array or hash variable without any value assigned is an undefined variable, which is interpreted as 0, '', or FALSE depending on the context.
Perl also supports a special value called "undef", which is used to indicate the status of an undefined variable.
The "undef" value and undefined variables can be used in a Perl script under these rules:
Here is a Perl tutorial script on how to use undef value and undefined variables:
#- UndefinedVariable.pl #- Copyright (c) HerongYang.com. All Rights Reserved. # #- Undefined scalar variable $price; $string = '('.$price.')'; # Interpreted as "" print($string, "\n"); $price = $price + 3.99; # Interpreted as 0 print($price, "\n"); undef($price); # Undefined again print("undef", "\n") if ($price == undef); # Interpreted as undef print("priceless!", "\n") if (! $price); # Interpreted as FALSE #- Undefined array variable @links; # Undefined @links = (@links, "herongyang.com", "perl.org", "cpan.org"); print(@links, "\n"); # Interpreted as empty list undef(@links); # Undefined again print("undef", "\n") if (@links == undef); # Interpreted as undef print("empty array!", "\n") if (! @links); # Interpreted as FALSE #- Undefined hash variable %siteRanks; # Undefined %siteRanks = (%siteRanks, "herongyang.com", 4, "perl.org", 6, "google.com", 9); print(%siteRanks, "\n"); # Interpreted as empty list undef(%siteRanks); # Undefined again print("undef", "\n") if (%siteRanks == undef); # Interpreted as undef print("empty hash!", "\n") if (! %siteRanks); # Interpreted as FALSE
Here is the output of the tutorial script:
() 3.99 undef priceless! herongyang.comperl.orgcpan.org undef empty array! herongyang.com4google.com9perl.org6 undef empty hash!
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