FranceMadrid9
FranceMadrid9

Reputation: 51

How to find and delete occurrence of duplicate value in a string within a foreach loop in perl

I have a foreach loop with a string inside of it:

foreach my $val(sort keys %hash) {

$string = $hash{$val}{'value'};

print "$string\n";

}

The output for printing my $string is:

23422
65464
32453
76654
21341
65437
23422
67658

I want to be able to find where there are two duplicate values, in this case, '23422' and delete them from the string entirely. So that when I print the string, it will print:

    65464
    32453
    76654
    21341
    65437
    67658

I am not sure how to go about this however because of the logic inside the foreach loop. I have tried testing if statements to check for equals and not equals but it is to no avail because it is not detecting the values to do it being inside a foreach loop.

Upvotes: 2

Views: 85

Answers (2)

zdim
zdim

Reputation: 66883

Make a pass to count occurrences of each value, then go over your hash and delete all entries with their value count larger than 1 (that value appears elsewhere in the hash)

use warnings;
use strict;
use feature 'say';

my @data = qw(23422 65464 32453 76654 21341 65437 23422 67658);

# Make up a hash with above values    
my %h = map { $_ => $data[$_] } 0..$#data;

# Get the count for each value
my %val_cnt;
++$val_cnt{$_} for values %h; 

# Delete hash entries for which the value appears more than once
for (keys %h) {
    delete $h{$_} if $val_cnt{$h{$_}} > 1;

    # Or, to keep %h intact and only print
    # say $h{$_} if $val_cnt{$h{$_}} == 1;
}

say join ' ', values %h;

prints

76654 67658 32453 65464 21341 65437

See delete and values

If you'd rather keep the hash and only print desired values then instead of delete-ing from the hash just print, for elements whose value count is 1 (the commented out line)

Upvotes: 2

stack0114106
stack0114106

Reputation: 8711

You can store the result in one more hash variable and then print if the entry is unique.

Check this out:

$hash{100}{'value'}=23422;
$hash{65464}{'value'}=65464;
$hash{32453}{'value'}=32453;
$hash{76654}{'value'}=76654;
$hash{21341}{'value'}=21341;
$hash{65437}{'value'}=65437;
$hash{102}{'value'}=23422;
$hash{67658}{'value'}=67658;

foreach my $val(sort keys %hash) {

$string = $hash{$val}{'value'};

$my_unique{$string}++

}

foreach my $val( keys %my_unique)
{

print "$val\n" if $my_unique{$val} == 1

}

Results in the shell

$ perl -f dup_delete.pl
65437
65464
21341
67658
32453
76654

Upvotes: 2

Related Questions