--- jatuporn <[EMAIL PROTECTED]> wrote:
> I try to write a program that reads a file with two fields.The first
> field is a costumer ID and the second is the costumer name by using "
> ! " as a seperator between 2 fields. Store costumer ID as the key and
> the costumer name as value into a hash. 
> My code is below, I have a problem that $info{ $key} does not show
> the value. What is the problem ? How to change it? Thank you.

1) Please format code to SOME readability before posting it to the
list.
2) Your example file data below is not seperated with " ! " as you
state
   above, but with just "!". Please be specific and precise.

Now:

>  ***** myfile.pl ***** 
>  $filename ="costumer.txt"; 
>  open(FILE,$filename ) or die ("can not open file : $filename");
>  while ($line = <FILE>) {
>    ($id,$name) = split(/!/,$line,2);

This splits the line like this:

  $id   = "001"
  $name = "Paul 002!Leo 003!Nick"

>    $info{$id} = $name; 

Now $info{$id} = "Paul 002!Leo 003!Nick"

>  }
>  print "Enter id:";
>  $key = <STDIN>;

$key will have the newline on it unless you chomp($key).
$id doesn't have a newline, so they will never match.
Do the chomp. =o)

>  print ("ID: $key  NAME : $info{ $key} \n");
>
>  ***** costumer.dat *****
>  001!Paul 002!Leo 003!Nick  

Try it this way:

   use strict; # make it a habit;
   my $filename = "costumer.txt"; 
   open FILE,$filename or die "$! : $filename"; # $! is the problem
   my %info;
   while ($line = <FILE>) {
     foreach my $pair (split /\s+/, $line) { # divide on the spaces
        my ($id,$name) = split(/!/,$line);   # now on the !'s
        $info{$id} = $name; 
     }
   }
   print "Enter id:";
   $key = <STDIN>;
   chomp $key;
   if ($info{$key}) {
       print ("ID: $key  NAME : $info{ $key} \n");
   } else {
       print "No such key '$key' in the data.\n";
   }
   exit;



=====
print "Just another Perl Hacker\n"; # edited for readability =o)
=============================================================
Real friends are those whom, when you inconvenience them, are bothered less by it than 
you are. -- me. =o) 
=============================================================
"There are trivial truths and there are great Truths.
 The opposite of a trival truth is obviously false.
 The opposite of a great Truth is also true."  -- Neils Bohr

__________________________________________________
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail
http://personal.mail.yahoo.com/

Reply via email to