On Tue, 25 Mar 2003, Pam Derks wrote:

> Hi all,
> 
> am struggling with this, and it must be the something simple but for the life of me 
> I don't see it.
> 
> Am trying to build a hash table with:
> instructor name and their biography
> 
> I've tried just about everything, but I can't get the values to show...
> 
> where am I going wrong?
> 
> thanks, Pam
> 
> snippet:
> #!/usr/bin/perl -w
> use strict;
> 
> open(BIOS, "instructor.txt") or die ("no instructor file:  $!");
> 
> 
> build_hash();
> 
> 
> sub build_hash{
>       my ($line, @name, @words, $key, $value, $name, $words);
>       my %hash = ();
> 
>       while(<BIOS>){
>               chomp;
>               if ($_ =~ /^[A-Z]{3,3}/){ #an instructor name
>                       $name = $_;
>                       $name =~ s/[ ]+$//; #remove trailing whitespace
>                       print("N: $name\n");
>                       
>               }
>               elsif ($_ !~ "XX"){
>                       $words = $_;
>                       $words =~ s/[ ]+$//; #remove trailing whitespace
>                       print("W: $words\n");
>               }
>               
>               $hash{$name} = $words;

This statement is executed for every single line of instructor.txt, 
including the blank lines. You don't have a next statement in the if 
and elsif blocks. For every blank line it sees this assignment happens
$hash{$name} = '';

This is the reason your values are turning out to be blank.

>               
> 
>       }
> 
>       foreach (keys %hash){
>               print("HN: $_\n");
>       }
> 
> 
>       foreach (values %hash){
>               print("HV: $_\n");
>       }
> 
> } #end build_hash
> 
> close BIOS;
> 

# Tweaked version of your code
open(BIOS, "instructor.txt") or die ("no instructor file:  $!");
build_hash();

sub build_hash{
        my ($line, @name, @words, $key, $value, $name, $words);
        my %hash = ();

        while(<BIOS>){
                chomp;
                # remove trailing whitespaces
                s/\s*$//;
                # ignore blank lines
                next if (/^$/);
                
                if ($_ eq 'XX' && defined ($name)) {
                    $hash{$name} = $words;
                    $words = $name = undef;
                    next;
                }

                if (/^[A-Z ]+$/) {
                    $name = $_;
                    next;
                }
                $words .= $_;
        }

        foreach (keys %hash){
                print("HN: $_\n");
        }

        foreach (values %hash) {
               print ("HV: $_\n");
        }

}
close BIOS;



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to