in reply to Hash Variable

Here ye go:
#!/usr/bin/perl use strict; my %hash; open (DATA, "<.txt") or die "Can't open file $!\n"; my @DATA = <DATA>; close (DATA); foreach my $rec (@DATA) { chomp $rec; my @vars = split(/,/,$rec); if ($vars[0]) { # you can use map to use the regex # on each element of the array map $_ =~ s/^\s+$//g, @vars; print "$vars[0] $vars[1] $vars[2] $vars[3]\n"; if( $hash{$vars[2]} ) { warn "key '$vars[2]' already exists in hash\n"; } else { $hash{$vars[2]} = join(' ', @vars[0,1,3]); # or whatever you wanted } # your hash to be built as } }
I threw the if( $hash{$vars[2]} ) in there in case you don't really know if the 3rd element is uniq throughout.

I'm assuming that with the s/^\s+$//g your intent is to to truncate all records that are all spaces. Is this correct?

- FrankG

Replies are listed 'Best First'.
Re: Re: Hash Variable
by qball (Beadle) on Apr 06, 2001 at 01:13 UTC
    I see where you're creating hash:
    $hash{$vars[2]} = join(' ', @vars[0,1,3]);
    How would I print that out?
    foreach $var2 (keys %hash){ print "value: $hash{$var2}\n"; }
    ...doesn't work too well.

    qball~"I have node idea?!"
      What do you mean "doesn't work too well"? That should work.
      Is an error occuring, is there not output, or is it not the way you want it to look?

      - FrankG

        It's not printing unique values. However, it is printing "key ' ' already exists in hash" after each line.

        So basically it's printing all the rows even those with $var2 that aren't unique.

        qball~"I have node idea?!"
Re: Re: Hash Variable
by qball (Beadle) on Apr 06, 2001 at 22:46 UTC
    Okay, I previously made a comment that FrankG's code didn't work. I decided to dig further and break the code down piece by piece. After a few hours of working with FrankG's code, I learned that my data.txt file wasn't a true CSV file. Some of the fields were combined and were fixed widths.

    Excel came in handy as I imported data.txt file and created data.csv. I then ran FrankG's code and voila!

    Now I'm going back and break the code down again, this time using a real CSV file.

    I'll keep you all posted on my progress. Many thanks to all of your comments. And please comment further if need be.

    qball~"I have node idea?!"