Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a text file like:
297220,ITEM
207420,NEW
and about 100 more lines like that separeted by coma
My goal here is to open this text file and store it into a hash, my code is not working.
Can someone take a look at that and help me out, here is the code I have
my (%pal, $key_pal, $data, %key_pal, $pal); open (FILE, "< pal.txt") || print "There is no PAL file here"; while ( my $line = <FILE> ) { chomp $line; $key_pal, $data = split ",", $line; $key_pal{$pal} = $data; }

And at the end of the loop I need to do this:
if ($pal{$key_pal} eq $my_item) { ...some code here}

This is my problem thanks!!!

Replies are listed 'Best First'.
Re: Hash Problem
by matija (Priest) on Mar 05, 2004 at 20:15 UTC
    Your problem is here:
    $key_pal, $data = split ",", $line; $key_pal{$pal} = $data;
    You put the index in the variable $key_pal, but you use $pal as index. Change the first line to:
    $pal,$date=split ",",$line;
Re: Hash Problem
by Limbic~Region (Chancellor) on Mar 05, 2004 at 20:13 UTC
    Anonymous Monk,
    Assuming there are no imbedded commas:
    my %pal; while ( <FILE> ) { chomp; my ($key, $val) = split /,/ , $_, 2; $pal{$key} = $val; if ( $val eq $my_item ) { # some code } }
    Cheers - L~R

    Update Added code to address testing values secondary question

Re: Hash Problem
by maa (Pilgrim) on Mar 05, 2004 at 20:18 UTC

    Have you got your variable names right??

    my %pal=(); while ( my $line = <DATA> ) { chomp($line); my($palkey, $data) = split (",", $line); $pal{$palkey} = $data; } while (my($key, $value) = each %pal) { print "$key=>$value\n"; } __DATA__ 297220,ITEM 207420,NEW 222222,OLD
Re: Hash Problem
by neniro (Priest) on Mar 05, 2004 at 20:39 UTC
    I would push all value pairs on to an array, and assign them later to the hash:
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %keypal; my @line; while(<DATA>) { chomp; push(@line, (split(/,/))[0,1]); } %keypal = @line; print Dumper(\%keypal); __DATA__ 297220,ITEM 207420,NEW
    best regards,
    neniro
      I have OCD related to while loops and hash assignments. Also a liking of maps, to an unhealthy level. :P

      I always liked this syntax better for stuff like this.

      %h = map { chomp $_; split( ',', $_, 2 ) } <DATA>; # or %h = map { /^([^,]+)\s*,\s*([^\n\r,]+)/ } <DATA>;

      Wonko

      Thank you all very much!!
      I found where the problem was based in your answers!!
      Thanks again!!!