⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fig13_13.pl

📁 PERL语言资料 可以用于PERL程序设计
💻 PL
字号:
#!/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.                     #
###########################################################################

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -