Drew Rush
Drew Rush

Reputation: 720

Check Hash for Value so as to not to add repeated value

What I'm trying to do is only add a value to a list in a hash as long as it's not already in that list. Can't figure out how to modify this code that I found to do that. I tried using grep and also exists with the hash, but can't manage to do it.

my %data; ## This will be a hash of lists, holding the data
my @names; ## This will hold the names of the columns
while (<>) {

$_ =~ s/\?"Period"//;
$_ =~ s/"BegBalance".*\n//;
$_ =~ s/\?[^"].*//;

chomp;
my @list=split(/\?/); ## Collect the elements of this line
for (my $i=0; $i<=$#list; $i++) {
    ## If this is the 1st line, collect the names
    if ($.==1) {
        $names[$i]=$list[$i];
    }
    ## If it is not the 1st line, collect the data
    else {
        push @{$data{$names[$i]}}, $list[$i];
    }
    }

}

foreach (@names){
    local $"="\t"; ## print tab separated lists
    print "$_\t@{$data{$_}}\n";
}

Upvotes: 0

Views: 45

Answers (1)

salparadise
salparadise

Reputation: 5805

This grep should work

  ## If it is not the 1st line, collect the data
    else {
       unless (grep {$_ eq $list[$i]} @{$data{$names[$i]}}) {
         push @{$data{$names[$i]}}, $list[$i];
     }
    }

If it does not, we may need to look at your input data.

Upvotes: 1

Related Questions