5.6. More Hashes
5.6.1. Loading a Hash from a File
Example 5.63.
(The Database)
1 Steve Blenheim
2 Betty Boop
3 Igor Chevsky
4 Norma Cord
5 Jon DeLoach
6 Karen Evich
(The Script)
#!/usr/bin/perl
# Loading a Hash from a file.
1 open(NAMES,"emp.names") || die "Can't open emp.names: $!\n";
2 while(<NAMES>){
3 ( $num, $name )= split(' ', $_, 2);
4 $realid{$num} = $name;
}
5 close NAMES;
6 while(1){
7 print "Please choose a number from the list of names? ";
8 chomp($num=<STDIN>);
9 last unless $num;
10 print $realid{$num},"\n";
}
(Output)
7 Please choose a number from the list of names? 1
10 Steve Blenheim
Number for which name? 4
Norma Cord
Number for which name? 5
Jon DeLoach
Number for which name? 2
Betty Boop
Number for which name? 6
Karen Evich
Number for which name? 8
Number for which name? 3
Igor Chevsky
Number for which name?
<Ctrl>-d or <Ctrl>-z (Exit the program)
A file called emp.names is opened for reading via the NAMES filehandle. A line at a time is read from the file via the while loop. The line just read in, $_, is split into two fields with whitespace (spaces, tabs, and newline) as the delimiter. After splitting up the $_ line, the split function returns a list, $num and $name (consisting of both the first and last names). A hash called %realid is created on the fly with $num as the key and $name as the value associated with that key. Each time through the loop, a new key/value pair is added to %realid. The filehandle is closed. The while loop is reentered. The user is asked for a number to be associated with a name. The number is read from standard input (the keyboard) as the user types it and is assigned to $num and chomped. The loop exits if $num does not have a value. The "name" value, $name, associated with the "number" key, $num, from the %realid hash is printed.
|
5.6.2. Special Hashes
The %ENV Hash
The %ENV hash contains the environment variables handed to Perl from the parent process; e.g., a shell or a Web server. The key is the name of the environment variable, and the value is what was assigned to it. If you change the value of %ENV, you will alter the environment for your Perl script and any processes spawned from it but not the parent process. Environment variables play a significant roll in CGI Perl scripts, discussed in Chapter 16.
Example 5.64.
Code View: (In Script)
#!/usr/bin/perl
1 foreach $key (keys(%ENV){
2 print "$key\n";
}
3 print "\nYour login name $ENV{'LOGNAME'}\n";
4 $pwd=$ENV{'PWD'};
5 print "\n", $pwd, "\n";
(Output)
2 OPENWINHOME
MANPATH
FONTPATH
LOGNAME
USER
TERMCAP
TERM
SHELL
PWD
HOME
PATH
WINDOW_PARENT
WMGR_ENV_PLACEHOLDER
3 Your login name is ellie
5 /home/jody/home
Iterate through the foreach loop to get the keys of the %ENV hash. Print the value of the key LOGNAME. Assign the value of the key PWD to $pwd.
|
The %SIG Hash
The %SIG hash allows you to set signal handlers for signals. If, for example, you press <Ctrl>-C when your program is running, that is a signal, identified by the name SIGINT. (See UNIX manual pages for a complete list of signals.) The default action of SIGINT is to interrupt your process. The signal handler is a subroutine that is automatically called when a signal is sent to the process. Normally, the handler is used to perform a clean-up operation or to check some flag value before the script aborts. (All signal handlers are assumed to be set in the main package.)
The %SIG array contains values only for signals set within the Perl script.
Example 5.65.
(In Script)
#!/usr/bin/perl
1 sub handler{
2 local($sig) = @_; # First argument is signal name
print "Caught SIG$sig -- shutting down\n";
exit(0);
}
4 $SIG{'INT'} = 'handler'; # Catch <Ctrl>-c
print "Here I am!\n";
5 sleep(10);
6 $SIG{'INT'}='DEFAULT';
7 $SIG{'INT'}='IGNORE';
< Program continues here >
handler is the name of the subroutine. The subroutine is defined. $sig is a local variable and will be assigned the signal name. When the SIGINT signal arrives, this message will appear, and the script will exit. The value assigned to the key INT is the name of the subroutine, handler. When the signal arrives, the handler is called. The sleep function gives you 10 seconds to press <Ctrl>-c to see what happens. The default action is restored. The default action is to abort the process if the user presses <Ctrl>-c. If you assign the value "IGNORE" to the $SIG hash, then <Ctrl>-c will be completely ignored and the program will continue.
|
The %INC Hash
The %INC hash contains the entries for each filename that has been included via the do or require functions. The key is the filename; the value is the location of the actual file found.
5.6.3. Context
In summary, the way Perl evaluates variables––the "funny" characters––depends on how the variables are being used; they are evaluated by context, either scalar or list.
If the value on the left-hand side of an assignment statement is a scalar, the expression on the right-hand side is evaluated in a scalar context; whereas if the value on the left-hand side is an array, the right-hand side is evaluated in a list context.
See "Reading from STDIN" on page 94 for a good review of how context is handled.
You'll see examples throughout the rest of this book where context plays a major role.
Example 5.66.
Code View: (The perldoc function describes how reverse works)
1 $ perldoc -f reverse
reverse LIST
In list context, returns a list value consisting of the
elements of LIST in the opposite order. In scalar context,
concatenates the elements of LIST and returns a string value with all
characters in the opposite order.
......
(The Perl Script)
@list = (90,89,78,100,87);
$str="Hello, world";
print "Original array: @list\n";4
print "Original string: $str\n";5
2 @revlist = reverse(@list);
3 $revstr = reverse($str);
4 print "Reversed array is: @revlist\n";
5 print "Reversed string is: $revstr\n";
6 $newstring = reverse(@list); print "List reversed, context
string: $newstring\n";
(Output)
Original array: 90 89 78 100 87
Original string: Hello, world
Reversed array is: 87 100 78 89 90
Reversed string is: dlrow ,olleH
List reversed, context string: 78001879809
Context is demonstrated in the documentation for Perl's built-in reverse function. The reverse function reverses the elements of an array and returns the reversed elements to another array. Context is array. This time, the reverse function reverses the characters in a string. It returns the reverse string as a scalar. Context is scalar. The elements of the reversed array are displayed. The reversed string is displayed. Here the reverse function reverses the array again, but the returned value will be assigned to a string. The context being scalar, the function will reverse the array elements and convert the list into a string of characters.
|