ramki067
ramki067

Reputation: 69

Displaying duplicate records

I've a code as below to parse a text file. Display all words after "Enter:" keyword on all lines of the text file. I'm getting displayed all words after "Enter:" keyword, but i wan't duplicated should not be repeated but its repeating. Please guide me as to wht is wrong in my code.

#! /usr/bin/perl
use strict;
use warnings;
$infile  "xyz.txt";
open (FILE, $infile) or die ("can't open file:$!");
if(FILE =~ /ENTER/ ){
    @functions = substr($infile, index($infile, 'Enter:'));
    @functions =~/@functions//;
    %seen=();
    @unique = grep { ! $seen{$_} ++ } @array;
    while (@unique != ''){
        print '@unique\n';
    }
}
close (FILE);

Upvotes: 0

Views: 190

Answers (2)

Toto
Toto

Reputation: 91438

Here is a way to do the job, it prints unique words found on each line that begins with the keyword Enter:

#!/usr/bin/perl
use strict;
use warnings;

my $infile = "xyz.txt";

# use 3 arg open with lexical file handler
open my $fh, '<', $infile or die "unable to open '$infile' for reading: $!";

# loop thru all lines
while(my $line = <$fh) {
    # remove linefeed;
    chomp($line);
    # if the line begins with "Enter:"
    # remove the keyword "Enter:"
    if ($line =~ s/^Enter:\s+//) {
        # split the line on whitespaces
        # and populate the array with all words found
        my @words = split(/\s+/, $line);
        # create a hash where the keys are the words found
        my %seen = map { $_ => 1 }@words;
        # display unique words
        print "$_\t" for(keys %seen);
        print "\n";
    }
}

Upvotes: 2

Mark Leighton Fisher
Mark Leighton Fisher

Reputation: 5703

If I understand you correctly, one problem is that your 'grep' only counts the occurrences of each word. I think you want to use 'map' so that '@unique' only contains the unique words from '@array'. Something like this:

@unique = map {
    if (exists($seen{$_})) {
        ();
    } else {
        $seen{$_}++; $_;
    }
 } @array;

Upvotes: -1

Related Questions