?? fig13_13.pl
字號(hào):
#!/usr/bin/perl
# Figure 13.13: fig13_13.pl
# Demonstrates a hash of arrays
use warnings;
use strict;
instructions();
my $choice = prompt();
my %hash;
while ( $choice ne 'q' ) {
addElement() if ( $choice eq 'a' );
deleteElement() if ( $choice eq 'd' );
deleteKey() if ( $choice eq 'k' );
printAll() if ( $choice eq 'p' );
instructions() if ( $choice eq 'i' );
$choice = prompt();
}
sub instructions
{
print <<DONE;
Enter 'a' to add an element.
Enter 'd' to delete an element.
Enter 'k' to delete a key.
Enter 'p' to print all elements.
Enter 'q' to quit.
DONE
}
sub prompt
{
print( "? " );
chomp( my $answer = <STDIN> );
return $answer;
}
sub addElement
{
print( "What is the key you would like to add? " );
chomp( my $key = <STDIN> );
print( "What is the value? " );
chomp( my $value = <STDIN> );
push @{ $hash{ $key } }, $value;
}
sub deleteElement
{
print( "What is the key of the element? " );
chomp( my $key = <STDIN> );
print( "What is the value of the element? " );
chomp( my $value = <STDIN> );
for ( 0 .. $#{ $hash{ $key } } ) {
if ( $hash{ $key }[ $_ ] eq $value ) {
print( "Deleting element $hash{ $key }[ $_ ]\n" );
splice( @{ $hash{ $key } }, $_, 1 );
return;
}
}
}
sub deleteKey
{
print( "What key would you like to delete? " );
chomp( my $key = <STDIN> );
delete( $hash{ $key } );
}
sub printAll
{
foreach ( keys( %hash ) ) {
print( " $_ => ", join( ', ', @{ $hash{ $_ } } ), "\n" );
}
}
###########################################################################
# (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall. #
# All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
###########################################################################
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -